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


Python timeit.timer函数代码示例

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


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

示例1: test_quick_sort

 def test_quick_sort(self):
     global a, sorted_a
     start = timer()
     a = quick_sort(a)
     time_taken = timer() - start
     print_array("Quick Sort", a, time_taken)
     self.assertListEqual(a.tolist(), sorted_a)
开发者ID:DarkLordZul,项目名称:444140_SEProject,代码行数:7,代码来源:Testing.py

示例2: async_million_time_changed_helper

async def async_million_time_changed_helper(hass):
    """Run a million events through time changed helper."""
    count = 0
    event = asyncio.Event(loop=hass.loop)

    @core.callback
    def listener(_):
        """Handle event."""
        nonlocal count
        count += 1

        if count == 10**6:
            event.set()

    hass.helpers.event.async_track_time_change(listener, minute=0, second=0)
    event_data = {
        ATTR_NOW: datetime(2017, 10, 10, 15, 0, 0, tzinfo=dt_util.UTC)
    }

    for _ in range(10**6):
        hass.bus.async_fire(EVENT_TIME_CHANGED, event_data)

    start = timer()

    await event.wait()

    return timer() - start
开发者ID:boced66,项目名称:home-assistant,代码行数:27,代码来源:__init__.py

示例3: exhaustive_eval

def exhaustive_eval(player_card, table_card):
	"""compute all possible games given the player/table cards (as a numbers from 0 to 51) and return equity win/tie for each player"""

	p = player_card.shape[0]
	equity_arr = np.zeros([p, 2], dtype=np.float32)

	print '\n---------------- Exhaustive eval start'
	print 'player_card=\n{}'.format(player_card)
	print 'table_card=\n{}'.format(table_card)
	print 'p={}'.format(p)

	t0 = timer()

	equity_arr = exhaustive_block_fast(player_card, table_card,
												keys.CARD_FLUSH_KEY,
												keys.CARD_FACE_KEY,
												keys.CARD_SUIT,
												keys.SUIT_MASK,
												keys.SUIT_BIT_SHIFT,
												EvalSeven.flush_rank,
												EvalSeven.face_rank,
												EvalSeven.flush_suit)

	t1 = timer()
	print 'run time = \t{:.6f} s'.format(t1-t0)
	print equity_arr
	print '\n---------------- Exhaustive eval end'

	return equity_arr
开发者ID:UrbanDiver,项目名称:Poker2,代码行数:29,代码来源:EvalExhaustive.py

示例4: get_voxel_locations

def get_voxel_locations(folder, fname, voxel=[0.176,0.176,0.38], ssave=False):
  # uses raw threshold function
  # get images as list
  fils = os.listdir(folder)
  def keep_tifs(rawlist):
    tiflist = []
    for f in rawlist:
      if len(f.split('.'))>1:
        if f.split('.')[1] == 'tif':
          tiflist.append(f)
    return tiflist
  tiflist = keep_tifs(fils) # this indexing may be removed if needed
  newtiflist = [folder+f for f in tiflist]
  newtiflist.sort() # alphabetize
  # commandeer all cores
  stime = timer()
  # pool = Pool()
  darr = [make_binary_thresh(i) for i in newtiflist] # adjust threshold in function
  # pool.close()
  # pool.join()
  print('Time taken for retrieving coordinates: %.2f' %(timer()-stime))
  # send to matrix2coords to get tuples back
  coords = matrix2coords(darr, voxel)
  if ssave:
    # save this
    save_coords(coords, fname)
  
  return coords, darr
开发者ID:mlabadi2,项目名称:code,代码行数:28,代码来源:imageMatrix.py

示例5: _logbook_filtering

def _logbook_filtering(hass, last_changed, last_updated):
    from homeassistant.components import logbook

    entity_id = 'test.entity'

    old_state = {
        'entity_id': entity_id,
        'state': 'off'
    }

    new_state = {
        'entity_id': entity_id,
        'state': 'on',
        'last_updated': last_updated,
        'last_changed': last_changed
    }

    event = core.Event(EVENT_STATE_CHANGED, {
        'entity_id': entity_id,
        'old_state': old_state,
        'new_state': new_state
    })

    def yield_events(event):
        # pylint: disable=protected-access
        entities_filter = logbook._generate_filter_from_config({})
        for _ in range(10**5):
            if logbook._keep_event(event, entities_filter):
                yield event

    start = timer()

    list(logbook.humanify(None, yield_events(event)))

    return timer() - start
开发者ID:boced66,项目名称:home-assistant,代码行数:35,代码来源:__init__.py

示例6: breedChildren

    def breedChildren(self,innovations):

        self.breedtime = 0.0
        self.mutatetime = 0.0

        crossoverchance = float(self.settings["crossover"])

        new_gen_children = []
        # breed all the children for each species
        for s in self.l_species:
            new_gen_children.extend(s.breedChildren(innovations))
            self.breedtime += s.breedtime
            self.mutatetime += s.mutatetime

        # fill the remainder with wild children
        remainder = self.population-len(new_gen_children)
        all_Gs = self.getAllGenomes()
        for i in range(remainder):
            bt0 = timer()
            if random.random() <= crossoverchance and len(all_Gs)>1:
                child= genome.crossover(random.sample(all_Gs, 2), self.settings)
            else:
                child = genome.copyGenome(random.choice(all_Gs), self.settings)
            bt1 = timer()
            self.breedtime += (bt1-bt0)
            child.mutate(innovations)
            bt2 = timer()
            self.mutatetime += (bt2-bt1)
            new_gen_children.append(child)

        self.newGeneration(new_gen_children)
开发者ID:basscheffer,项目名称:BONEAT,代码行数:31,代码来源:species.py

示例7: bf

def bf(n):
    start=timer()
    epsilon=0.00001
    a=0
    b=0
    for x1 in range(0,n+1):
        for y1 in range(0,n+1):
            if x1==0 and y1==0:
                continue
            v1=np.array([x1,y1])
            for x2 in range(0,n+1):
                for y2 in range(0,n+1):
                    if x2==0 and y2==0:
                        continue
                    v2=np.array([x2,y2])
#                    if np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))>1-epsilon:
#                        continue
                    if np.array_equal(v1,v2):
                        continue
                    if abs(np.dot((v1-v2),v2))<epsilon:
                        b+=1
                        continue
    print('Count: ',int(n**2) +b)
    print('b: ',b)
    print('Elapsed time: ',timer()-start,'s')
开发者ID:mbh038,项目名称:PE,代码行数:25,代码来源:PE_0091.py

示例8: main

def main(command, args):
    print("Apk Mass Installer Utility \nVersion: 3.1\n")

    adb_kill()  # kill any instances of adb before starting if any

    # wait for adb to detect phone
    while True:
        if adb_state():
            break
        print("No phone connected waiting to connect phone")
        time.sleep(1)

    print("Starting adb server...")
    adb_start()  # start an instance of adb server

    t_start = timer()

    if "backup" in command:
        archive = args.pop("archive", False)
        encrypt = args.pop("encrypt", False)
        back_up(archive, encrypt)

    elif "restore" in command:
        path = args.pop("path")
        restore(path)

    human_time(t_start, timer())

    adb_kill()
开发者ID:binary-signal,项目名称:mass-apk-installer,代码行数:29,代码来源:mass_apk_installer.py

示例9: test_ec_bin_translation

def test_ec_bin_translation():
    from timeit import default_timer as timer

    G = EcGroup()
    o = G.order()
    g = G.generator()
    pt1000 = [o.random() * g for _ in range(1000)]

    exp = []
    for pt in pt1000:
        exp += [pt.export()]

    t0 = timer()
    for ept in exp:
        EcPt.from_binary(ept, G)
    t1 = timer()
    print("\nParsed compressed Pt: %2.4f" % (t1 - t0))

    exp = []
    for pt in pt1000:
        exp += [pt.export(EcPt.POINT_CONVERSION_UNCOMPRESSED)]

    t0 = timer()
    for ept in exp:
        EcPt.from_binary(ept, G)
    t1 = timer()
    print("\nParsed uncompressed Pt: %2.4f" % (t1 - t0))
开发者ID:lucamelis,项目名称:petlib,代码行数:27,代码来源:ec.py

示例10: create_all_preflop_two_hand_equity

def create_all_preflop_two_hand_equity(verbose=False, save=False, distributed=False, nb_process=4):
	"""returns preflop_two_hand_equity for all two hand preflop combinations"""
	global all_preflop_two_hands

	print '\n--------------- start create_all_preflop_two_hand_equity'
	print 'all preflop two hands = \nstart = {}\nend = {}\nnb of elements = {}'.format(all_preflop_two_hands[:5], all_preflop_two_hands[-5:], len(all_preflop_two_hands))

	t0 = timer()

	if (distributed):
		pool = ThreadPool(nb_process)
		equity = pool.map(preflop_two_hand_equity, all_preflop_two_hands[:])
		pool.close()
		pool.join()
	else:
		equity = []
		for k, p in enumerate(all_preflop_two_hands[:]):
			if (verbose):
				# print k,' - ', p
				sys.stdout.write('\rk=%5d / %5d : {}' % (k+1, len(all_preflop_two_hands)), p)
				sys.stdout.flush()
			equity.append(preflop_two_hand_equity(p))

	t1 = timer()
	print 'all_preflop_two_hand_equity time = {:9.4f} s'.format(t1-t0)
	print 'exact number of distinct (rankwise) pairs of preflop hands = {}'.format(np.array([len(e) for e in equity]).sum())
	if (save):
		cPickle.dump(equity, open(os.path.join('Tables', 'all_preflop_two_hand_equity.pk'), 'wb'))
		print '{} saved to disk as {}'.format('equity', os.path.join('Tables', 'all_preflop_two_hand_equity.pk'))
	return equity
开发者ID:UrbanDiver,项目名称:Poker2,代码行数:30,代码来源:EvalAnalysis.py

示例11: comm_test

    def comm_test(self, show=True):

        logging.info("Starting communication test...")

        # TODO: Use part of nearest neighbour data for test data
        # data = (leds.nearestNeighbours[:, 0] % 256).astype('int8').tobytes()
        # mid_point = leds.numLeds[0]
        data = bytes(range(1, 101))

        responses = []
        timings = []
        for tys in self.tys:
            start = timer()
            self.send_bytes(tys, b'X' + data + b'\n')
            response = tys.serial.readline().rstrip()
            end = timer()
            responses.append(response)
            timings.append(end - start)

        if show:
            for i, x in enumerate(zip(responses, timings)):
                print("Teensy %d: %s, %.4fs" %
                      (i, x[0].decode('utf8'), x[1]))

        if all([r == b'OK' for r in responses]):
            logging.info("Communication test successful.")
            return True
        else:
            logging.info("Communication test failed.")
            return False
开发者ID:billtubbs,项目名称:display1593,代码行数:30,代码来源:display1593.py

示例12: bench1

def bench1():
    print "Bench 1"
    its = 30
    cons = Box(np.array([[0, 10], [0, 10]]))
    x_init = np.array([1, 1])
    goal = Box(np.array([[9, 9.5], [1, 1.5]]))
    obstacles = [Polytope(np.array([[1, 5,0], [1, 5,9.4], [1, 6,9.4], [1, 6,0]]), False)]

    drm_nodes = []
    rrt_nodes = []
    drm_times = []
    rrt_times = []
    for i in range(its):
        print "it {0}".format(i)
        start = timer()
        drm = DRMotion(cons, obstacles, 1, 0.5, 1)
        t, cur = drm.build_tree(x_init, goal)
        end = timer()
        drm_nodes.append(len(t.nodes()))
        drm_times.append(end - start)
        start = timer()
        rrt = RRT(cons, obstacles, 1)
        t, cur = rrt.build_tree(x_init, goal)
        rrt_nodes.append(len(t.nodes()))
        end = timer()
        rrt_times.append(end - start)

    print "drm nodes: max {0} min {1} avg {2}".format(
        max(drm_nodes), min(drm_nodes), sum(drm_nodes) / float(its))
    print "drm times: max {0} min {1} avg {2}".format(
        max(drm_times), min(drm_times), sum(drm_times) / float(its))
    print "rrt nodes: max {0} min {1} avg {2}".format(
        max(rrt_nodes), min(rrt_nodes), sum(rrt_nodes) / float(its))
    print "rrt times: max {0} min {1} avg {2}".format(
        max(rrt_times), min(rrt_times), sum(rrt_times) / float(its))
开发者ID:fran-penedo,项目名称:drmotion,代码行数:35,代码来源:benchmarks.py

示例13: bench2

def bench2():
    print "Bench 2"
    its = 30
    cons = Box(np.array([[0, 10], [0, 10]]))
    x_init = np.array([1, 1])
    goal = Box(np.array([[9, 9.5], [1, 1.5]]))
    obstacles = [Polytope(np.array([[1, 5,0], [1, 5,10], [1, 5.3,10], [1, 5.3,0]]), False)]

    drm_nodes = []
    drm_times = []
    for i in range(its):
        print "it {0}".format(i)
        start = timer()
        try:
            drm = DRMotion(cons, obstacles, 1, 0.5, 1)
            t, cur = drm.build_tree(x_init, goal)
        except DRMNotConnected as e:
            drm_nodes.append(len(e.tree_progress.nodes()))
            pass
        end = timer()
        drm_times.append(end - start)

    print "drm nodes: max {0} min {1} avg {2}".format(
        max(drm_nodes), min(drm_nodes), sum(drm_nodes) / float(its))
    print "drm times: max {0} min {1} avg {2}".format(
        max(drm_times), min(drm_times), sum(drm_times) / float(its))
开发者ID:fran-penedo,项目名称:drmotion,代码行数:26,代码来源:benchmarks.py

示例14: p88old

def p88old(nmax):
    """returns minmal sum-product numbers up to n digits"""
    start=timer()
#    pset=set()
    psns={}
    primes=primesfrom2to(nmax)
    for n in range(2,nmax+1):
        psn,m,solution=psnmin(n,primes)
        psns[n]=(psn,m,solution)
#        print(n,psn,m,solution)
#    return
    count=0
    psums=[]
    for k,v in psns.items():
        a,b=v[2][0],v[2][1]
        newn=0
        m=2
        for c in [2,3]:
            while newn<nmax:                
                m+=1
                newn,newpsn,newsol=psnmin2(a,b,c,m)
    #            print(k,newn,newpsn,newsol)
                if newn<=nmax and newpsn<psns[newn][0]:
                    count+=1
                    psns[newn]=(newpsn,m,newsol)
    #                print(k,newn,psns[newn])
        psums.append(sum(set([v[0] for k,v in psns.items()])))
#    print (pset)
#    print(sum(pset))
    plt.plot(psums)
    print(psums[-1])
    print('replacements:',count)
    print('Elapsed time:',timer()-start)
    return psns    
开发者ID:mbh038,项目名称:PE,代码行数:34,代码来源:PE_0088.py

示例15: handle_result

    def handle_result(self, solver, t, y):
        """
        Post processing (stores the time points).
        """
        time_start = timer()
        
        if self._extra_f_nbr > 0:
            y_extra = y[-self._extra_f_nbr:]
            y       = y[:-self._extra_f_nbr]
            
        #Moving data to the model
        if t != self._model.time or (not self._f_nbr == 0 and not (self._model.continuous_states == y).all()):
            #Moving data to the model
            self._model.time = t
            #Check if there are any states
            if self._f_nbr != 0:
                self._model.continuous_states = y

            #Sets the inputs, if any
            self._set_input_values(t)
        
            #Evaluating the rhs (Have to evaluate the values in the model)
            rhs = self._model.get_derivatives()

        self.export.integration_point(solver)
        if self._extra_f_nbr > 0:
            self._extra_equations.handle_result(self.export, y_extra)
            
        self.timings["handle_result"] += timer() - time_start
开发者ID:modelon,项目名称:PyFMI,代码行数:29,代码来源:assimulo_interface.py


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