def main(): print("using type {}".format(type(data[0]))) Timing.startlog() for i in range(len(c)): result.append(c[i] * d[i]) Timing.endlog() print(result[0:10])
def main(): print("There are {} samples".format(len(c))) print("using type {}".format(type(data[0]))) Timing.startlog() for i in range(len(c)): result.append(c[i] * d[i]) Timing.endlog()
def Profile_Activation_Functions(): # First, initialize two networks. One will use Rational activation functions # and the other will use Tanh. Rational_NN = Network.Neural_Network(Num_Hidden_Layers=5, Neurons_Per_Layer=100, Input_Dim=3, Output_Dim=1, Activation_Function="Rational") Tanh_NN = Network.Neural_Network(Num_Hidden_Layers=5, Neurons_Per_Layer=100, Input_Dim=3, Output_Dim=1, Activation_Function="Tanh") # Now generate some random data. Data = torch.rand((20000, 3), dtype=torch.float32, requires_grad=True) # Pass the data through both networks, time it. Rational_Timer = Timing.Timer() Tanh_Timer = Timing.Timer() Rational_Timer.Start() Rational_NN(Data) Rational_Time = Rational_Timer.Stop() Tanh_Timer.Start() Tanh_NN(Data) Tanh_Time = Tanh_Timer.Stop() # Print results. print("Rational: %fs" % Rational_Time) print("Tanh: %fs" % Tanh_Time)
def main(): print("Starting test code") print("using type {}".format(type(data[0]))) print("Starting timer") Timing.start() for i in range(len(c)): result.append(c[i] * d[i]) print(result) print("End test code")
def main(): print("using type {}".format(type(data[0]))) f = open("../log.csv", "a+") f.write("Python,{},".format(type(data[0]))) f.close() Timing.startlog() for i in range(len(c)): result.append(c[i] * d[i]) Timing.endlog()
def createTimeTable(): import Timing periods = len(Timing.makePeriods()) days = Timing.daysOfMonth() import pandas as pd dataF = pd.DataFrame(index=days, columns=['P%s' % (i + 1) for i in range(periods)]) dataF = dataF.rename_axis('Days', axis='index') dataF = dataF.fillna(theDefaultEmptyChar()) dataF.to_csv(TIME_TABLE_FILE_NAME)
def main(): print("using type {}".format(type(data[0]))) #f = open("../data/python.csv", 'a') Timing.startlog() for i in range(len(c)): result.append(c[i] * d[i]) elapsed = Timing.endlog() #f.write(str(elapsed)) #f.write("\n") #f.close() saveData(result)
def main(): print("There are {} samples".format(len(c))) print("using type {}".format(type(data[0]))) for _ in range(iterations): result.clear() # since this will be run many times, it is important to clear this, otherwise it'll have too many values Timing.startlog() for i in range(len(c)): result.append(c[i] * d[i]) Timing.endlog(times)
def timing(self, delta_time, s_time, d_time, d_channels): self.delta_time = delta_time #get the sync pulse information # s_time,s_channels=self.read_file(self.file_location) #create two dictionaries: 1 for region one and the other for region 2 self.region1_spectrum = {} self.region2_spectrum = {} for i in range(self.num_channels): self.region1_spectrum[i] = 0 self.region2_spectrum[i] = 0 #convert the lists in np arrays for cython to work with sync_time = np.asarray(s_time) detec_time = np.asarray(d_time) detec_channels = np.asarray(d_channels) sync_num = sync_time.size #loop through the sync pulse times # d_loc=0 # split_loc=0 s = time.time() try: r1, r2 = Timing.channel_timing(sync_time, sync_num, detec_time, detec_channels, delta_time, self.num_channels) except: sync_num -= 1 r1, r2 = Timing.channel_timing(sync_time, sync_num, detec_time, detec_channels, delta_time, self.num_channels) for i in range(len(r1)): self.region1_spectrum[i] = r1[i] self.region2_spectrum[i] = r2[i] print('Process time {:.2f}'.format(time.time() - s)) s = time.time() #convert the sync time and pulse times to np arrays for cython pulse_bins = 100 pulse_timing = np.linspace(0, (s_time[2] - s_time[1]), pulse_bins) pulse_times = Timing.time_point(sync_time, detec_time, sync_num, pulse_timing, pulse_bins) print('Process timing in: {:.2f}s'.format(time.time() - s)) del sync_time del detec_time del s_time del d_time del d_channels return [ self.region1_spectrum, self.region2_spectrum, [pulse_times, pulse_timing] ]
def __init__(self, desk): # self.base = base self.desk = desk self.clearEntropySeqs() self.time = timePack.Timing() self.myPlot = graphPac.Plot()
def __init__(self, startTime = None): """ Sets up the event queue, which is a dictionary using keys of the form int(time.time). The keys point to SortCacheLists, which store the events. """ self.queuedEvents = {} if startTime is None: startTime = Timing.mostAccurateTime() self.lastTime = startTime
def generateTimeTable(): 'class whose timetable is to be generated' import math import Timing timeList = Timing.makePeriods() daysOfMonth = Timing.daysOfMonth() import pandas as pd timeTable = readTimeTable() subjects = readBooksFile() import random random.shuffle(subjects) for dayIndex in range(len(daysOfMonth)): d = daysOfMonth[dayIndex] tempSubjects = list(subjects) for p in timeTable.columns: if (len(tempSubjects) != 0): random.shuffle(tempSubjects) temp = tempSubjects.pop() if ((timeTable.loc[d, p] == theDefaultEmptyChar())): factor = math.ceil(temp[1] / len(daysOfMonth)) markup = "<a target='_blank' href='%s'> %s<br>%d to %d </a>" % ( temp[2], temp[0], dayIndex * factor, (dayIndex + 1) * factor) timeTable.loc[d, p] = markup else: if (len(tempSubjects) != 0): print("Not enough slots") newColumns = dict() for i in range(len(timeList)): key = 'P%d' % (i + 1) newColumns[key] = timeList[i] timeTable = timeTable.rename(columns=newColumns) dataFrameToHtmlString(timeTable)
def getNextEvents(self, currentTime=None): """ Returns the events which have yet to be executed and occur before currentTime. """ if currentTime is None: currentTime = Timing.mostAccurateTime() events = [] appendToEvents = events.append self._list.sort() for it in xrange(len(self._list)): if self._list[0].getTime() <= currentTime: appendToEvents(self._list.pop(0)) else: break return events
def __init__(self,fileName, resourceManager, configurationManager, stats, jobSubmissionTime,dedicatedMode): # job2Submit of type JsdlParser.Job self.jsdlFile = fileName self.profiler = Timing.timeprofile() self.resourceManager = resourceManager self.configurationManager = configurationManager self.stats = stats self.jobSubmissionTime = jobSubmissionTime self.dedicatedMode = dedicatedMode self.runOnInstance = None self.jobHashValue = None try: self.jobToSubmit = JsdlParser.Job(self.jsdlFile) except: print "Error while parsing file %s:" % self.jsdlFile, sys.exc_info()[0] hashKey = "{0}{1}{2}".format(self.jobToSubmit.executableName,self.jobToSubmit.dataStaging,self.jobToSubmit.arguments) self.jobHashValue = hashlib.sha1(hashKey).hexdigest()
def getNextEvents(self, currentTime=None): """ Returns the events which have yet to be executed and occur before currentTime. """ if currentTime is None: currentTime = Timing.mostAccurateTime() events = [] appendToEventList = events.append for it in xrange(len(self.queue)): event = self.queue.pop() if currentTime >= event.getTime(): appendToEventList(event) else: # add event back to queue self.queue.append(event) break return events
def getNextEvents(self, currentTime=None): """ Returns the events which have yet to be executed and occur before currentTime. """ if currentTime is None: currentTime = Timing.mostAccurateTime() eventList = [] appendToEventList = eventList.append currentTimeIndex = int(currentTime) for timeIndex in xrange( int(self.lastTime), currentTimeIndex ): timeIndexEvents = self.queuedEvents.get(timeIndex,None) if timeIndexEvents is not None: timeIndexEvents.sort() for event in timeIndexEvents: appendToEventList(event) del self.queuedEvents[timeIndex] currentEvents = self.queuedEvents.get(currentTimeIndex,None) if currentEvents is not None: currentEvents.sort() for i in xrange(len(currentEvents)): event = currentEvents[0] if event.time <= currentTime: appendToEventList(currentEvents.pop(0)) else: break self.lastTime = currentTime return eventList
def getNextEvents(self, currentTime=None): """ Returns the events which have yet to be executed and occur before currentTime. """ if currentTime is None: currentTime = Timing.mostAccurateTime() events = [] queueEmptyFunc = self._queue.empty while not queueEmptyFunc(): event = self._queue.get_nowait() if event.getTime() <= currentTime: events.append(event) else: self._queue.put_nowait(event) break return events
def ROI_Spectrum_Saving(self): '''Saving the roi pulses and their respective timing to later perform an integration to find the MDM''' if not self.calibration: self.calibration_browse() list_time=np.asarray(self.list_time) list_channel=np.asarray(self.list_channel) calibration=np.asarray(self.calibration_data) sync_time=np.asarray(self.sync_time) lower,ok=QInputDialog.getDouble(self, 'Lower ROI', 'Lower Bound (MeV)',9.6,0,14,4) upper,ok2=QInputDialog.getDouble(self, 'Upper ROI', 'Upper Bound (MeV)',10.9,0,14,4) if ok and ok2: # #outputs the pulses and associated times to save and integrate to # #calculate the detection probability at integrated time windows s=time.time() print('Begin processing data') pulses,times=Timing.ROI_Timing(sync_time,int(len(sync_time)), list_time,list_channel, self.delta_time,8192, calibration,upper,lower) print('Done processing in {:.2f}s'.format(time.time()-s)) return pulses,times
def initialization(self,resourceSpec,configurationManager): self.profiler = Timing.timeprofile() self.profiler.mark("resource_mng_connect") self.configurationManager = configurationManager self.keyPairFile = configurationManager.getKeyPairFile() self.VmInstanceUser = configurationManager.getVmInstanceUser() logging.debug("Private key file is %s" % self.keyPairFile) self.buildResourceSpec(resourceSpec) # Connect to Amazon EC2 self.AWS_ACCESS_KEY_ID = configurationManager.getEC2AccessKeyId() self.AWS_SECRET_ACCESS_KEY = configurationManager.getEC2SecretAccessKey() logging.debug("Checking validity of private key %s." % self.keyPairFile) key= paramiko.RSAKey(None, None,self.keyPairFile,'', None, None) self.instances = [] self.vmInstancesList = [] self.vmInstances = {} self.runningInstancesDic = { 'm1.small':0, 'c1.medium':0,'m1.large':0,'m1.xlarge':0,'c1.xlarge':0 } self.runningInstancesFile = configurationManager.getRunningInstancesFile() self.instanceWriteCount = 1
# ***************************************************************** # IonControl: Copyright 2016 Sandia Corporation # This Software is released under the GPL license detailed # in the file "license.txt" in the top-level IonControl directory # ***************************************************************** import os import sys import Timing sys.path.insert(0, os.path.abspath('..')) #create the test object whcih will control the niSync card test = Timing.Timing() #write to the object's data to configure the niSync card test.sampleRate = 100e3 try: #initialize will connect all clock and trigger terminals test.init('PXI1Slot2') #send a trigger programatically test.sendSoftwareTrigger() #except Timing.niSyncError as e : # if e.code == -1073807240: # print 'Warning:' # print e # else: # raise
queue_stat = Queue() queue_gop = Queue() esci = False stat_process = Process(target=Statistiche.stat, args=((queue_stat, ip_receiver, port_stat, num_porte), )) #image_process = Process(target=Image_Handler.analyzer, args=((queue_gop, pcap_path, gop_dir, img_dir), )) # da usare #image_process.start() # da usare stat_process.start() try: num_canali, quali = queue_stat.get() except KeyboardInterrupt: exit(-1) packets = rdpcap(sys.argv[1], 1) timer = Timing() start = time.time() start_time = 0 pkt_start_time = packets[0].time #numero_totale_pkt = 0 bind_layers(UDP, RTP) try: with PcapReader(pcap_path) as pcap_reader: for index, pkt in enumerate(pcap_reader): if IP in pkt and RTP in pkt: #numero_totale_pkt = index try: num_canali, quali = queue_stat.get(block=False) except queue.Empty: pass if start_time == 0: # per avere uno start time più fedele possibile
def __init__(self, data=None, delay=0): self.time = Timing.mostAccurateTime()+delay self.data = data
import sys import time import math import Timing seed = 696320 N = 4096 print '%10s%10s%10s%10s' % ('N', 'cost(s)', 'ratio', 'lg ratio') prev_cost = None for i in range(6): st = time.time() Timing.trial(N, seed) cost = time.time() - st if prev_cost: ratio = cost / prev_cost print '%10d%10.2f%10.2f%10.2f' % (N, cost, ratio, math.log(ratio) / math.log(2)) else: print '%10d%10.2f' % (N, cost) N *= 2 prev_cost = cost ''' $ jython ex1.py N cost(s) ratio lg ratio 10000 0.88
def prepareVerticalMutualInfo(self, desk, sufix, which_module, showmessage=False): self.desk = desk de_novo = desk.de_novo # desk.showmsg_obs('Prepare Mutual Information: num indiv: %i length: %i' % (self.ent.mySequence.getNumOfSeqs(),self.ent.mySequence.getLengthSequence())) ''' setNames define completeFilename +++ SPECIE !''' if not self.entFile.setPrefixSufix( root=desk.rootTable, prefix='VMI', sufix=sufix): return filename = self.entFile.MI_prefix_sufix_txt(self.entFile.prefix_sufix, 'mi') filename = desk.rootTable + filename time = crono.Timing() time.start() if not os.path.exists(filename) or de_novo: stri = "new: lines %i cols %i, %s" % (len( self.ent.mySequence.seqs), len( self.ent.mySequence.seqs[0]), filename) desk.showmsg_obs(stri) self.dicPiList, \ self.HShannonList, self.HShannonCorrList,\ self.SeHShannonList, self.SeHShannonCorrList, \ self.MIlist, self.MIcorrList, self.SeMIList, self.SeMICorrList, self.ijList = \ self.ent.calcVerticalMutualInfo(desk, self.ent.mySequence.seqs, showmessage=showmessage) self.entFile.write_VMI_files(sufix, self.dicPiList, self.HShannonList, self.HShannonCorrList, \ self.SeHShannonList, self.SeHShannonCorrList, \ self.MIlist, self.MIcorrList, \ self.SeMIList, self.SeMICorrList, self.ijList, showmessage=False) else: stri = "reading MI: %i lines, %i cols, %s" % (len( self.ent.mySequence.seqs), len( self.ent.mySequence.seqs[0]), filename) desk.showmsg_obs(stri) if which_module == 'all': ret, msg, self.HShannonList, self.HShannonCorrList = \ self.entFile.read_VMI_files(desk.rootTable, sufix, 'hShannon', showmessage=False) if ret: ret, msg, self.SeHShannonList, self.SeHShannonCorrList = \ self.entFile.read_VMI_files(desk.rootTable, sufix, 'seh', showmessage=False) ret, msg, self.MIlist, self.MIcorrList = \ self.entFile.read_VMI_files(desk.rootTable, sufix, 'mi', showmessage=False) if ret: ret, msg, self.SeMIList, self.SeMICorrList = \ self.entFile.read_VMI_files(desk.rootTable, sufix, 'se', showmessage=False) elif which_module == 'Entropy': ret, msg, self.HShannonList, self.HShannonCorrList = \ self.entFile.read_VMI_files(desk.rootTable, sufix, 'hShannon', showmessage=False) if ret: ret, msg, self.SeHShannonList, self.SeHShannonCorrList = \ self.entFile.read_VMI_files(desk.rootTable, sufix, 'seh', showmessage=False) else: ret, msg, self.MIlist, self.MIcorrList = \ self.entFile.read_VMI_files(desk.rootTable, sufix, 'mi', showmessage=False) if ret: ret, msg, self.SeMIList, self.SeMICorrList = \ self.entFile.read_VMI_files(desk.rootTable, sufix, 'se', showmessage=False) if ret: ret, msg, self.dicPiList, self.ijList = \ self.entFile.read_VMI_files(desk.rootTable, sufix, 'pij', showmessage=False) if not ret: print msg + '. Recalculating ....', self.dicPiList, \ self.HShannonList, self.HShannonCorrList,\ self.SeHShannonList, self.SeHShannonCorrList, \ self.MIlist, self.MIcorrList, self.SeMIList, self.SeMICorrList, self.ijList = \ self.ent.calcVerticalMutualInfo(self.desk, self.ent.mySequence.seqs, showmessage=showmessage) time.finish() print '>>>', time.milli(), 'ms' return True, 'ok'
print "Simulating..." while (not simulation.complete()): simulation.tick() frames += 1 sf += 1 delta = time.time() - printTime if delta > 0.2: objects = len(simulation.world.all) fps = sf / delta pot += 1 if pot > 5: print " => Running simulation @ %5.2ffps - completed %d frames, have %d objects" % (fps, frames, objects) if fps < minFps: minFps = fps printTime = time.time() sf = 0 totalTime = (time.time() - start) print print print "Simulation complete - averaged %.3ffps, min was %.3ffps" % (frames/totalTime, minFps) """ Timing.printAll()
''' Created on Jan 20, 2016 @author: jaya ''' from product.com.src.static.downloaders.Gnip import Gnip from product.com.src.static.parsers.GinipJsonParser import JsonParser from product.com.loggings.log_conf import Logger from product.com.utils.DbHelper import DbHelper import Timing as monitor from time import clock tstart = clock() log = Logger.logr log.debug("starting Test of GNIP Parser") g = Gnip().run() log.debug(g) gnip_json_parser = JsonParser(g) filename = gnip_json_parser.parseJson() tstop = clock() log.critical("Processing complete in %s",monitor.secondsToStr(tstop-tstart)) dbhelper = DbHelper() print filename dbhelper.import_content(filename) dbhelper.export_content("D:\\exportedMongo.csv")
def addEvent(self,event): timeDelay = event.getTime()-Timing.mostAccurateTime() if timeDelay >= 0: Timer(timeDelay,self.executedEvents.append,[event]).start()
def __init__(self, data=None, delay=0): self.time = Timing.mostAccurateTime()+delay self.data = data def getTime(self): return self.time def __cmp__(self, other): return self.time > other.time if __name__ == '__main__': import random startTime = currentTime = Timing.mostAccurateTime() delay = 5.250 eq=EventQueue2a(startTime) numEv=500 # add 500 events to the queue to execute after "delay" seconds. for t in xrange(numEv): eq.addEvent(TestEvent(delay=delay)) numEvents = 0 while numEvents < numEv: currentTime = Timing.mostAccurateTime() numEvents+=len(eq.getNextEvents(currentTime)) print 'Elapsed time: %.6f'%(currentTime-startTime)
class Pong: # Utility classes timer = Timing.Timing() board = Draw.Board(Constants.length, Constants.height) # Gameplay classes player_one = Bat() player_two = Bat() ball = Ball() player_one_controller = JoystickController.JoystickController( 0x10, 10, 9, True, True) player_two_controller = JoystickController.JoystickController( 0x20, 0x00, 0x00, True, True) # Game state vars serving = True playerTwoIsServing = False serves = 0 gameOver = False def start(self): # Let's hope this works... Sound.play_async(Sound.start_music) self.board.prepare() # Setup the board by putting the bats and ball in the right place self.board.updateBats(self.player_one.position, self.player_two.position, self.player_one.is_big, self.player_two.is_big) self.board.updateBall(self.ball.position[0], self.ball.position[1]) self.board.updateScore(0, False) self.board.updateScore(0, True) # Run the game loop until the game is over while not self.gameOver: self.game_loop() def game_loop(self): # Get the last frame time self.timer.update_time() # Update the status of the joystick controllers self.player_one_controller.update() self.player_two_controller.update() # Emulate random bat movement and update the big_time on the Bat self.player_one.update( self.timer.deltaTime, self.player_one_controller.get_resistor_screen_position() + 1) if self.ball.direction_x == 1: # If the ball is coming towards the AI ai_pos_delta = (self.ball.position[1] - self.player_two.position) else: ai_pos_delta = (Constants.height // 2 - self.player_two.position) if ai_pos_delta != 0: # If we're not /ing by 0 if random.randint(0, 1) == 1: # 50/50 chance to move self.player_two.update( self.timer.deltaTime, self.player_two.position + int(abs(ai_pos_delta) / ai_pos_delta)) # If the current game state is serving, set up a serve if self.serving: self.setup_serve() # Emulate a serve if not self.playerTwoIsServing: if self.player_one_controller.button_1_pressed == 0: self.ball.set_direction([1, random.randrange(-1, 1)]) self.serving = False self.serves += 1 if self.serves % 5 == 0: self.playerTwoIsServing = not self.playerTwoIsServing else: if random.randrange(1, 100) == 9: self.ball.set_direction([-1, random.randrange(-1, 1)]) self.serving = False self.serves += 1 if self.serves % 5 == 0: self.playerTwoIsServing = not self.playerTwoIsServing # If the current game state is not serving (ie. playing) else: # Move the ball self.ball.update(self.timer.deltaTime) if self.ball.position[1] == 0: self.ball.direction_y *= -1 self.ball.set_position( [self.ball.position[0], self.ball.position[1] + 1]) elif self.ball.position[1] == Constants.height - 1: self.ball.direction_y *= -1 self.ball.set_position( [self.ball.position[0], self.ball.position[1] - 1]) if self.ball.position[0] == 2 or self.ball.position[0] == 1: deltaOne = self.player_one.check_hit(self.ball.position[1]) if deltaOne: self.reverse_ball_direction(deltaOne) Sound.play_async(Sound.hit_sequence) elif self.ball.position[ 0] == Constants.length - 3 or self.ball.position[ 0] == Constants.length - 2: deltaTwo = self.player_two.check_hit(self.ball.position[1]) if deltaTwo: self.reverse_ball_direction(deltaTwo) Sound.play_async(Sound.hit_sequence) # Check if the player wants to be big if self.player_one_controller.button_2_pressed == 0: self.player_one.make_big() if self.player_two_controller.button_2_pressed == 0: self.player_two.make_big() # Write the current game state to the board self.board.prepare() self.board.updateBats(self.player_one.position, self.player_two.position, self.player_one.is_big, self.player_two.is_big) self.board.updateBall(self.ball.position[0], self.ball.position[1]) self.board.updateScore(self.player_one.score) self.board.updateScore(self.player_two.score, True) # If a player has scored, update their score and change the state to serving if self.ball.position[0] == 0: self.player_two.score += 1 Glow.score() self.set_serving() elif self.ball.position[0] == Constants.length - 1: self.player_one.score += 1 Glow.score() self.set_serving() # Check if either player has won the game self.check_winner() # Draw the board and wait until it needs to be drawn again self.board.draw() self.timer.wait_for_update() def set_serving(self): self.serving = True self.player_one.set_position(None) self.player_two.set_position(None) def setup_serve(self): if not self.playerTwoIsServing: self.ball.set_position([3, self.player_one.position]) else: self.ball.set_position( [Constants.length - 4, self.player_two.position]) def reverse_ball_direction(self, delta=0): if delta < 0: self.ball.direction_y = -1 elif delta > 0: self.ball.direction_y = 1 else: self.ball.direction_y = 0 self.ball.direction_y = random.randrange(-1, 1) self.ball.direction_x *= -1 self.ball.set_speed(random.choice(Constants.speed)) def check_winner(self): # If either player has a score greater than 9, they win if self.player_one.score > 9: self.board.updateWinner(False) self.gameOver = True return True elif self.player_two.score > 9: self.board.updateWinner(True) self.gameOver = True return True return False
def updater(self): delta_time=self.duty_cycle.value()/100*( self.sync_time[2]-self.sync_time[1]) delt=(self.sync_time[2]-self.sync_time[1]) self.offset.setMinimum(-int((delt*self.duty_cycle.value()/100)*.75)) sync_width=delta_time delta_time+=self.offset.value() self.delta_time=delta_time start=float(self.start_time.value())*1e6 end=float(self.end_time.value())*1e6 sb,se=Timing.Splitter(self.sync_time,len(self.sync_time), start,end) cb,ce=Timing.Splitter(self.list_time,len(self.list_time), start,end) self.region1_spec,self.region2_spec,self.time=self.list_mode_processor.timing( delta_time,self.sync_time[sb:se], self.list_time[cb:ce],self.list_channel[cb:ce]) total=[] for i in range(len(list(self.region2_spec.values()))): total.append(list(self.region2_spec.values())[i]+list( self.region1_spec.values())[i]) self.region1_ax.clear() self.region2_ax.clear() self.total_ax.clear() self.region1_ax.set_title('Region 1') self.region2_ax.set_title('Region 2') self.total_ax.set_title('Total') r1_values=list(self.region1_spec.values())[:-1] r2_values=list(self.region2_spec.values())[:-1] uncal_keys=list(self.region1_spec.keys()) if self.calibration: self.region1_ax.set_xlim(self.calibration_data[0], 14) self.region2_ax.set_xlim(self.calibration_data[0], 14) self.total_ax.set_xlim(self.calibration_data[0],14) self.region1_ax.set_xlabel('Energy [MeV]') self.region2_ax.set_xlabel('Energy [MeV]') self.total_ax.set_xlabel('Energy [MeV]') self.region1_ax.plot(self.calibration_data,r1_values) self.region2_ax.plot(self.calibration_data,r2_values) self.total_ax.plot(self.calibration_data,total[:-1],label='Total') self.total_ax.plot(self.calibration_data,r1_values,label='Region 1') self.total_ax.plot(self.calibration_data,r2_values,label='Region 2') else: self.region1_ax.set_xlabel('Channel') self.region2_ax.set_xlabel('Channel') self.total_ax.set_xlabel('Channel') self.region1_ax.set_xlim(0,len(list(self.region1_spec.keys()))) self.region2_ax.set_xlim(0,len(list(self.region2_spec.keys()))) self.total_ax.set_xlim(0,len(list(self.region2_spec.keys()))) self.region1_ax.plot(uncal_keys[:-1],r1_values) self.region2_ax.plot(uncal_keys[:-1],r2_values) self.total_ax.plot(uncal_keys[:-1],total[:-1],label='Total') self.total_ax.plot(uncal_keys[:-1],r1_values,label='Region 1') self.total_ax.plot(uncal_keys[:-1],r2_values,label='Region 2') self.region1_ax.set_yscale('log') self.region2_ax.set_yscale('log') self.total_ax.set_yscale('log') self.region1_ax.set_ylabel('Counts') self.region2_ax.set_ylabel('Counts') self.total_ax.set_ylabel('Counts') self.total_ax.legend() self.region1_canvas.draw() self.region2_canvas.draw() self.total_canvas.draw() #plot the timing stuff self.time_ax.clear() self.time_ax.plot(self.time[1][:-1], self.time[0][:-1],'*',label='Time Distribution') height=max(self.time[0]) ys=[0,height,height,0] xs=[0,0,sync_width,sync_width] self.time_ax.plot(xs,ys, label='Sync Pulse, {:.1f}%'.format(self.duty_cycle.value())) self.time_ax.axvline(delta_time, label='Region divider, {:.1f}us\nafter pulse'.format(delta_time)) self.time_ax.set_xlabel(r'Time [$\mu$s]') self.time_ax.set_title('Time') self.time_ax.set_ylabel('Counts') self.time_ax.set_yscale('log') self.time_ax.legend() self.time_canvas.draw() winsound.MessageBeep()
import sys import time import math import Timing seed = 696320 N = 4096 print '%10s%10s%10s%10s' % ('N', 'cost(s)', 'ratio', 'lg ratio') prev_cost = None for i in range(6): st = time.time() Timing.trial(N, seed) cost = time.time() - st if prev_cost: ratio = cost / prev_cost print '%10d%10.2f%10.2f%10.2f' % (N, cost, ratio, math.log(ratio)/math.log(2)) else: print '%10d%10.2f' % (N, cost) N *= 2 prev_cost = cost ''' $ jython ex1.py N cost(s) ratio lg ratio