当前位置: 首页>>代码示例>>Python>>正文


Python timer.Timer类代码示例

本文整理汇总了Python中timer.Timer的典型用法代码示例。如果您正苦于以下问题:Python Timer类的具体用法?Python Timer怎么用?Python Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Timer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, screen, pos, zero_pos, rad,
                 cursor_rad, success_time, min_time):
        # constants
        self.HIGHLIGHT_COLOR = 20,255,20
        self.HIGHLIGHT_COLOR_FAIL = 255,20,20
        self.CURRENT_COLOR_ACTIVE = 40,180,40
        self.CURRENT_COLOR = 40,180,40
        self.NEXT_COLOR = 40,80,40
        self.NEXT_NEXT_COLOR = 40,50,40
        self.BG_COLOR = 40,40,40
        self.DEFAULT_COLOR = self.CURRENT_COLOR
        self.DEFAULT_OUTLINE_COLOR = 20,20,20

        # display
        self.screen = screen
        self.color = self.DEFAULT_COLOR
        self.outline_color = self.DEFAULT_OUTLINE_COLOR

        # game logic
        self.pos = (zero_pos[0]+pos[0],
                    zero_pos[1]+pos[1])
        self.outline_rad = 2
        self.rad = rad
        self.cursor_rad = cursor_rad
        self.success_timer = Timer(success_time)
        self.target_timer = Timer(success_time)
        self.active_timer = Timer(min_time)
        self.highlight = False
        self.wait_prev_target = True
        self.success = True
        self.complete_success = False
开发者ID:efunn,项目名称:hemo-control,代码行数:31,代码来源:target.py

示例2: acquisition

def acquisition(config):

    timer = Timer()
    getch = _Getch()
    last_char = ""
    last_char2 = ""
    nl_count = 0
    bs_count = 0
    char_count = 0
    quit = False

    while not quit:
        # on lit un caractère
        my_char = getch()
        char_count += 1
        # saut de ligne:
        if my_char == "\r":
            print
            nl_count += 1
            # reset le dernier caractère
            last_char = ""
            last_char2 = ""
            # autre caractère
        else:
            nl_count = 0
            # caractère BACKSPACE
            if my_char == "\x08" or my_char == "\x7f":
                # on compte le nb de backspace pour les stats
                bs_count += 1
                # écrire un backspace déplace simplement le curseur
                # il faut effacer avec un espace
                sys.stdout.write("\x08 \x08")
                # reset le dernier caractère
                last_char = ""
            else:
                sys.stdout.write(my_char)

                # si un précédent caractère était présent
                if last_char != "":
                    # récupérer le temps entre deux frappes
                    t = timer.time()

                    # ajout dans la configuration si l'intervalle semble correct
                    if t < 1:
                        config.add(last_char + my_char, t)

                    if last_char2 != "":
                        config.add(last_char2 + last_char + my_char, t)
                        # sauvegarde du dernier caractère
                last_char2 = last_char
                last_char = my_char

                # deux appuis simultanés sur ENTER quittent la boucle
        if nl_count == 2:
            quit = True

            # reset du chronomètre
        timer.start()

    return float(bs_count) / float(char_count) * 100
开发者ID:Pawamoy-Sandbox,项目名称:magelli,代码行数:60,代码来源:acquisition.py

示例3: TimerTest

class TimerTest(unittest.TestCase):

    def setUp(self):
        self.timer=Timer(1)

    def test_parse_timer(self):
        timer = Timer('''interval: 10
                         event: test_timer_event''')

        self.assertEqual(timer.period, 10)
        self.assertEqual(timer.event, 'test_timer_event')

    def test_timer_poll(self):
        reset_time = self.timer.reset()
        while time() < reset_time + 1 - 0.05:
            self.assertEqual(self.timer.poll(), None)
        count = 0
        while time() < reset_time + 1 + 0.05:
            poll = self.timer.poll()
            if not poll == None:
                if round(poll) == 0:
                    count = count + 1
            sleep(0.01)
        self.assertEqual(count,1)

    def test_timer_poll_count(self):
        reset_time = self.timer.reset()
        count = 0
        while(time() < reset_time + 3.1):
            if self.timer.poll() != None:
                count = count + 1
            sleep(0.05)
        self.assertEqual(count,3)
开发者ID:sonologic,项目名称:thermo2,代码行数:33,代码来源:test_timer.py

示例4: __init__

    def __init__(self, sim, manager):
        super(ScreenIO, self).__init__()

        # Keep track of the important parameters of the screen state
        # (We receive these through events from the gui)
        self.ctrlat  = 0.0
        self.ctrlon  = 0.0
        self.scrzoom = 1.0

        self.route_acid = None

        # Keep reference to parent simulation object for access to simulation data
        self.sim     = sim
        self.manager = manager

        # Timing bookkeeping counters
        self.prevtime = 0.0
        self.prevcount = 0

        # Output event timers
        self.slow_timer = Timer()
        self.slow_timer.timeout.connect(self.send_siminfo)
        self.slow_timer.timeout.connect(self.send_aman_data)
        self.slow_timer.timeout.connect(self.send_route_data)
        self.slow_timer.start(1000/self.siminfo_rate)

        self.fast_timer = Timer()
        self.fast_timer.timeout.connect(self.send_aircraft_data)
        self.fast_timer.start(1000/self.acupdate_rate)
开发者ID:ThomL,项目名称:bluesky,代码行数:29,代码来源:screenio.py

示例5: get_pos_examples

    def get_pos_examples(self):
        counts = self._get_pos_counts()
        for i in range(len(counts)):
            self.trainers[i].alloc_pos(counts[i])

        _t = Timer()
        roidb = self.imdb.roidb
        num_images = len(roidb)
        for i in range(num_images):
            #im = cv2.imread(self.imdb.image_path_at(i))
            #if roidb[i]['flipped']:
            #    im = im[:, ::-1, :]
            #im = self.imdb.image_path_at(i)
            gt_inds = np.where(roidb[i]['gt_classes'] > 0)[0]
            gt_boxes = roidb[i]['boxes'][gt_inds]
            _t.tic()
            scores, boxes, feat = self.im_detect(self.net, i, gt_boxes, self.feature_scale, gt_inds, boReturnClassifierScore = False)
            _t.toc()
            #feat = self.net.blobs[self.layer].data
            for j in range(1, self.imdb.num_classes):
                cls_inds = np.where(roidb[i]['gt_classes'][gt_inds] == j)[0]
                if len(cls_inds) > 0:
                    cls_feat = feat[cls_inds, :]
                    self.trainers[j].append_pos(cls_feat)
            if i % 50 == 0:
                print('get_pos_examples: {:d}/{:d} {:.3f}s' \
                      .format(i + 1, len(roidb), _t.average_time))
开发者ID:AllanYiin,项目名称:CNTK,代码行数:27,代码来源:train_svms.py

示例6: kruskal_wallis

def kruskal_wallis(genotype, phenVals, useTieCorrection=True):
    t = Timer()
    num_accessions=len(genotype.accessions)
    num_snps = genotype.num_snps
    assert num_accessions== len(phenVals), "SNPs and phenotypes are not equal length."
    ranks, group_counts = _kw_get_ranks_(phenVals)
    assert len(group_counts) == len(set(ranks)), 'Somethings wrong..'
    tieCorrection = 1.0
    if useTieCorrection:
        n_total = len(ranks)
        ones_array = np.repeat(1.0, len(group_counts))
        s = np.sum(group_counts * (group_counts * group_counts - ones_array))
        s = s / (n_total * (n_total * n_total - 1.0))
        tieCorrection = 1.0 / (1 - s)

    n = len(phenVals)
    ds = np.zeros(num_snps)
    c = 12.0 / (n * (n + 1))
    snps = genotype.get_snps_iterator()
    for i, snp in enumerate(snps):
        ns = np.bincount(snp)
        rs = np.array([0.0, np.sum(snp * ranks)])
        rs[0] = np.sum(ranks) - rs[1]
        nominator = 0.0
        mean_r = (n + 1) / 2.0
        for j in range(2):
            v = (rs[j] / ns[j]) - mean_r
            nominator += ns[j] * v * v
        ds[i] = (c * nominator) * tieCorrection

    ps = sp.stats.chi2.sf(ds, 1)

    log.info('Took %s' % t.stop(True))
    return {"ps":ps, "ds":ds}
开发者ID:timeu,项目名称:PyGWAS,代码行数:34,代码来源:gwas.py

示例7: getPostById

def getPostById():
    totalRuns = config.executions
    connection = pymysql.connect(**config.dbConfig)
    cursor = connection.cursor()
    timer = Timer()
    meanTime = 0
    percentConfig = totalRuns / 100
    print("==================================== Post By Id Query ====================================")
    print("SELECT obj FROM wp_posts WHERE id = post_id;")
    for run in range(totalRuns):
        postId = randint(1, config.totalPosts)
        query = "SELECT {} FROM wp_posts WHERE id = {}".format('text', postId)
        timer.restart()
        cursor.execute(query)
        meanTime += timer.get_seconds()
        percent = (run / totalRuns) * 100
        if (run % percentConfig) == 0:
            print("Completed: {:.0f} %                ".format(percent), end = '\r')
    print("Completed 100 %")
    print("Mean query execution time : {:.10f} seconds".format(meanTime / totalRuns))
    connection.close()
    print("")
    print("Example Query")
    print(query)
    print("")
    return meanTime / totalRuns
开发者ID:TapanBala,项目名称:backend-database-benchmarking,代码行数:26,代码来源:getPostById.py

示例8: request_file

    def request_file(self, file_requested = None):

            file_size = self.proxy.getFileSize(file_requested)
            print ('File size: ' + str(file_size) + ' Bytes')
            
            file_download = open(file_requested, 'w')
            
            timer = Timer()
            
            # 1.5 MB = 137 sec (1 KB)
            # 1.5 MB = 16 sec (10 KB)
            # 1.5 MB = 4 sec (50 KB)
            # 1.5 MB = 2.84 sec (100 KB)
            # 1.5 MB = 2.67 sec (150 KB)
            # 1.5 MB = 2.26 sec (500 KB)
            # 700 MB = 961 sec (16 min) (150 kb) 747 KB/s
            
            for size in range(0, file_size, self.DEFAULT_CHUNK_FILE_SIZE): # Loop each chunk size KB
                #print 'Requesting size: ' + str(size)
                async_result = self.proxy.begin_getFileChunk(file_requested, size, self.DEFAULT_CHUNK_FILE_SIZE) # Chunks
                #print 'Async call processed (' + str(size) + ')'
        
                try:
                    data = self.proxy.end_getFileChunk(async_result) # Ice::MemoryLimitException or timeout
                except Ice.CommunicatorDestroyedException as e: #@UndefinedVariable ::Ice::CommunicatorDestroyedException
                    sys.stderr.write('Error: The connection to comunicator was destroyed.\nClient abort.\n')
                    return -1
                
                except Exception as e:
                    sys.stderr.write('Error: unknown exception in request_file %s\nClient abort.\n' % str(e))
                    #print 'Message:' + e.message
                    #print 'Error:' + str(e.unknown)
                    #print 'ice_name:' + str(e.ice_name())
                    #print 'String:' + e.__str__()
                    
                    return -1
        
                speed = size / timer.duration_in_seconds()
                
                if size / 1024.0 < 1024:
                    size = str(round(size / 1024.0, 2)) + ' KB'
                elif size / (1024.0 * 1024.0) < 1024:
                    size = str(round(size / (1024.0 * 1024.0), 2)) + ' MB'
                elif size / float(1024.0 * 1024.0 * 1024.0) < 1024:
                    size = str(round(size / (1024.0 * 1024.0 * 1024.0), 2)) + ' GB'  
                
                file_download.write(data)
                
                if speed / 1024.0 < 1024:
                    speed = str(round(speed / 1024.0, 2)) + ' KB/s'
                elif speed / (1024.0 * 1024.0) < 1024:
                    speed = str(round(speed / (1024.0 * 1024.0), 2)) + ' MB/s'
                elif speed / (1024.0 * 1024.0 * 1024.0) < 1024:
                    speed = str(round(speed / (1024.0 * 1024.0 * 1024.0), 2)) + ' GB/s'   
                    
                print ('Received (' + str(size) + ') ' + 'Speed: ' + str(speed))  
                
            file_download.close()
            
            print ('Data saved in ' + str(timer.duration_in_seconds()) + ' seconds')
开发者ID:bossjones,项目名称:freestation-client,代码行数:60,代码来源:FreeStationClient.py

示例9: collectionQuery3

def collectionQuery3():
    totalRuns = config.executions
    connection = pymysql.connect(**config.dbConfig)
    cursor = connection.cursor()
    percentConfig = totalRuns / 100
    timer = Timer()
    meanTime = 0
    limit = 20
    print("=================================== Collection Query 3 ===================================")
    print(" SELECT text_id AS id, p_text AS text, p_published AS published FROM tag_query3 LEFT JOIN text ON text_id = text.id WHERE p_country = 1 p_type = 'postType' AND p_rank < `postRank` AND p_site = 'site' ORDER BY p_rank DESC LIMIT 20;")
    for run in range(totalRuns):
        postType = config.postTypes[randint(0, 9)]
        postRank = randint(1, config.totalPosts - 1)
        country = config.countries[randint(0, 3)]
        site = config.siteConfig[randint(0, 19)]
        query = "SELECT text_id AS id, p_text AS text, p_published AS published FROM tag_query3 LEFT JOIN text ON text_id = text.id WHERE p_{} = 1 AND p_type = '{}' AND p_rank < {} AND p_site = '{}' ORDER BY p_rank DESC LIMIT {}".format(country, postType, postRank, site, limit)
        timer.restart()
        cursor.execute(query)
        meanTime += timer.get_seconds()
        percent = (run / totalRuns) * 100
        if (run % percentConfig) == 0:
            print("Completed: {:.0f} %                ".format(percent), end = '\r')
    print("Completed 100 %")
    print("Mean query execution time : {:.10f} seconds".format(meanTime / totalRuns))
    connection.close()
    print("")
    print("Example Query")
    print(query)
    print("")
    return meanTime / totalRuns
开发者ID:TapanBala,项目名称:backend-database-benchmarking,代码行数:30,代码来源:collectionQuery3.py

示例10: solve

 def solve(self, presents_to_place):
     if self.make_timer:
         timer = Timer()
         num_total_presents = len(presents_to_place)
     gc_collect_count = 0
     presents_index = 0
     presents_last_index = len(presents_to_place)
     while 1:
         priority_pick = self.priority_pick
         new_layer = MaxRectSolver(self.width, self.height)
         try:
             presents_index = new_layer.solve(presents_to_place, presents_index, self.scorer, priority_pick)
             self._add_layer(new_layer)
             print("{} more presents".format(presents_last_index - presents_index))
             if presents_index == presents_last_index - 1:
                 break
         except NoFit:
             priority_pick -= 10
             assert priority_pick > 1
         if self.make_timer:
             ratio = presents_index / num_total_presents
             print("Time left: {}; End time: {}".format(timer.time_left(ratio), timer.time_end(ratio)))
     print("Solved with total depth {}".format(self.total_depth))
     if self.make_timer:
         print("Time taken: {}".format(timer.time_taken()))
     if self.gc_collect_cycle:
         gc_collect_count += 1
         if gc_collect_count == self.gc_collect_cycle:
             gc_collect_count = 0
             print("GC collect")
             gc.collect()
开发者ID:Gerenuk,项目名称:Kaggle-Santa,代码行数:31,代码来源:maxrect_layers.py

示例11: collectionQuery2

def collectionQuery2():
    fake = Faker()
    totalRuns = config.executions
    connection = pymysql.connect(**config.dbConfig)
    cursor = connection.cursor()
    limit = 20
    timer = Timer()
    meanTime = 0
    percentConfig = totalRuns / 100
    tags = []
    config.getTags(tags)
    print("=================================== Collection Query 2 ===================================")
    print("SELECT text_id AS id, p_text AS text FROM wp_tags AS t LEFT JOIN post2tag ON t.id = tag_id LEFT JOIN tag_query2 ON post_id = text_id LEFT JOIN text ON text_id = text.id WHERE t.name = 'tagName' AND p_site = 'site' AND p_country = 1 AND p_rank < rank ORDER BY p_rank DESC LIMIT 20")
    for run in range(totalRuns):
        tagName = tags[randint(0, config.totalTags - 1)]
        postRank = randint(1, config.totalPosts)
        site = config.siteConfig[randint(0, 19)]
        country = config.countries[randint(0, 3)]
        query = "SELECT text_id AS id, p_text AS text FROM wp_tags AS t LEFT JOIN post2tag ON t.id = tag_id LEFT JOIN tag_query2 ON post_id = text_id LEFT JOIN text ON text_id = text.id WHERE t.name = '{}' AND p_site = '{}' AND p_{} = 1 AND p_rank < {} ORDER BY p_rank DESC LIMIT {}".format(tagName, site, country, postRank, limit)
        timer.restart()
        cursor.execute(query)
        meanTime += timer.get_seconds()
        percent = (run / totalRuns) * 100
        if (run % percentConfig) == 0:
            print("Completed: {:.0f} %                ".format(percent), end = '\r')
    print("Completed 100 %")
    print("Mean query execution time : {:.10f} seconds".format(meanTime / totalRuns))
    connection.close()
    print("")
    print("Example Query")
    print(query)
    print("")
    return meanTime / totalRuns
    
开发者ID:TapanBala,项目名称:backend-database-benchmarking,代码行数:33,代码来源:collectionQuery2.py

示例12: save

    def save(self,file):
        """
            Arguments:
                
                file: where to save (utf-8 encoding)

            Examples:
                
                ngrams.save("myfile")
        """

        file = self.__test_file(file,'w')
        n_word = len(self)

        buffer = ""

        sys.stderr.write("Saving the %i-grams...\n" % self.__max_arity)

        t = Timer(n_word,out=sys.stderr)
        t.start()
        for i in range(self.__max_arity):
            for word in self.__get_sorted_grams(i,(0,i+1)):
                buffer += "#".join(word)+"%"+str(self.__ngrams[i][word])+"\n"

                if len(buffer) > 1000:
                    file.write(buffer)
                    buffer = ""

                t.print_update(1)

        file.write(buffer)
        file.close()
开发者ID:bouthilx,项目名称:toiledemots,代码行数:32,代码来源:ngrams.py

示例13: Fuzzie

class Fuzzie(TextEntity):
	def __init__(self, layer, vel_x, vel_y):
		TextEntity.__init__(self, None, layer, char = '*')
		#self.setPos(self.pos_x, s.pos_y)
		self.vel_x = vel_x
		self.vel_y = vel_y
		self.visible = True
		self.liveTimer = Timer()
		self.liveTimer.start()
		self.name = 'Fuzzie'
	
	def death(self, attacker=None, deathtype=None):
		self.health = -1

	def think(self, frameDT):
		if len(self.touching): self.collideHandler()
		if not self.health: self.death()

	def collideHandler(self):
		for partner in self.touching:
			if partner[0]:
				if partner[0].getChar() == '+':
					#print "Hit by bullet!"
					self.health = 0
		self.touching = []
开发者ID:spekode,项目名称:2dengine1,代码行数:25,代码来源:player.py

示例14: _get_feature_scale

    def _get_feature_scale(self, num_images=100):
        _t = Timer()
        roidb = self.imdb.roidb
        total_norm = 0.0
        total_sum = 0.0
        count = 0.0
        num_images = min(num_images, self.imdb.num_images)
        inds = np.random.choice(range(self.imdb.num_images), size=num_images, replace=False)

        for i_, i in enumerate(inds):
            #im = cv2.imread(self.imdb.image_path_at(i))
            #if roidb[i]['flipped']:
            #    im = im[:, ::-1, :]
            #im = self.imdb.image_path_at(i)
            _t.tic()
            scores, boxes, feat = self.im_detect(self.net, i, roidb[i]['boxes'], boReturnClassifierScore = False)
            _t.toc()
            #feat = self.net.blobs[self.layer].data
            total_norm += np.sqrt((feat ** 2).sum(axis=1)).sum()
            total_sum += 1.0 * sum(sum(feat)) / len(feat)
            count += feat.shape[0]
            print('{}/{}: avg feature norm: {:.3f}, average value: {:.3f}'.format(i_ + 1, num_images,
                                                           total_norm / count, total_sum / count))

        return self.svm_targetNorm * 1.0 / (total_norm / count)
开发者ID:AllanYiin,项目名称:CNTK,代码行数:25,代码来源:train_svms.py

示例15: runScript

def runScript(fn,argv=[]):
    """Play a formex script from file fn.

    fn is the name of a file holding a pyFormex script.
    A list of arguments can be passed. They will be available under the name
    argv. This variable can be changed by the script and the resulting argv
    is returned to the caller.
    """
    from timer import Timer
    t = Timer()
    msg = "Running script (%s)" % fn
    if pf.GUI:
        pf.GUI.scripthistory.add(fn)
        pf.board.write(msg,color='red')
    else:
        message(msg)
    pf.debug("  Executing with arguments: %s" % argv,pf.DEBUG.SCRIPT)
    pye = fn.endswith('.pye')
    if pf.GUI and getcfg('check_print'):
        pf.debug("Testing script for use of print function",pf.DEBUG.SCRIPT)
        scr = checkPrintSyntax(fn)
        #
        # TODO: if scr is a compiled object, we could just execute it
        #

    res = playScript(file(fn,'r'),fn,fn,argv,pye)
    pf.debug("  Arguments left after execution: %s" % argv,pf.DEBUG.SCRIPT)
    msg = "Finished script %s in %s seconds" % (fn,t.seconds())
    if pf.GUI:
        pf.board.write(msg,color='red')
    else:
        message(msg)
    return res
开发者ID:dladd,项目名称:pyFormex,代码行数:33,代码来源:script.py


注:本文中的timer.Timer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。