• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python timeit.timer函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: get_result

    def get_result(self):
        """
        Write result to file, load result data and create an FMICSResult
        object.

        Returns::

            The FMICSResult object.
        """
        time_start = timer()
        
        if self.options["return_result"]:
            # Get the result
            res = self.result_handler.get_result()
        else:
            res = None
            
        end_time = timer()
        self.timings["returning_result"] = end_time - time_start
        self.timings["other"] = end_time - self.time_start_total- sum(self.timings.values())
        self.timings["total"] = end_time - self.time_start_total

        # create and return result object
        return FMIResult(self.model, self.result_file_name, None,
            res, self.options, status=self.status, detailed_timings=self.timings)
开发者ID:modelon,项目名称:PyFMI,代码行数:25,代码来源:fmi_algorithm_drivers.py


示例17: run

    def run(self):
        start = timer()
        cxx_std = self.benchmark_definition['cxx_std']
        num_bindings = self.benchmark_definition['num_bindings']
        compiler_executable_name = self.benchmark_definition['compiler']
        benchmark_generation_flags = self.benchmark_definition['benchmark_generation_flags']

        other_compile_flags = []
        if 'use_old_style_fruit_component_install_syntax' in benchmark_generation_flags:
            other_compile_flags.append('-DUSE_OLD_STYLE_FRUIT_COMPONENT_INSTALL_SYNTAX')
            other_compile_flags.append('-Wno-deprecated-declarations')

        run_command(compiler_executable_name,
                    args = compile_flags + other_compile_flags + [
                        '-std=%s' % cxx_std,
                        '-DMULTIPLIER=%s' % (num_bindings // 5),
                        '-I', self.fruit_sources_dir + '/include',
                        '-I', self.fruit_build_tmpdir + '/include',
                        '-ftemplate-depth=1000',
                        '-c',
                        self.fruit_benchmark_sources_dir + '/extras/benchmark/compile_time_benchmark.cpp',
                        '-o',
                        '/dev/null',
                    ])
        end = timer()
        return {"compile_time": end - start}
开发者ID:txxia,项目名称:fruit,代码行数:26,代码来源:run_benchmarks.py


示例18: driver

def driver(pricer, do_plot=False):
    paths = np.zeros((NumPath, NumStep + 1), order='F')
    paths[:, 0] = StockPrice
    DT = Maturity / NumStep

    ts = timer()
    pricer(paths, DT, InterestRate, Volatility)
    te = timer()
    elapsed = te - ts

    ST = paths[:, -1]
    PaidOff = np.maximum(paths[:, -1] - StrikePrice, 0)
    print 'Result'
    fmt = '%20s: %s'
    print fmt % ('stock price', np.mean(ST))
    print fmt % ('standard error', np.std(ST) / np.sqrt(NumPath))
    print fmt % ('paid off', np.mean(PaidOff))
    optionprice = np.mean(PaidOff) * np.exp(-InterestRate * Maturity)
    print fmt % ('option price', optionprice)

    print 'Performance'
    NumCompute = NumPath * NumStep
    print fmt % ('Mstep/second', '%.2f' % (NumCompute / elapsed / 1e6))
    print fmt % ('time elapsed', '%.3fs' % (te - ts))

    if do_plot:
        pathct = min(NumPath, MAX_PATH_IN_PLOT)
        for i in xrange(pathct):
            pyplot.plot(paths[i])
        print 'Plotting %d/%d paths' % (pathct, NumPath)
        pyplot.show()
    return elapsed
开发者ID:shaowei-su,项目名称:Python-Computing-Acceleration,代码行数:32,代码来源:montePara.py


示例19: main

def main():

	start = timer()

	count = 0

	table = load_metadata_table('metadata/fiction_metadata.csv')
	with open('results/fictiondedup.csv', 'w') as outfile:
		for grouping in generate_clumps(table, 0.7):
			while len(grouping) > 0:
				compare_element = grouping.pop(0)
				count += 1
				print count
				text_group = []
				for i in xrange(len(grouping)-1, -1, -1):
				    if compare_element.test_similarity(grouping[i]):
				    	count += 1
				    	print count
				    	text_group.append(grouping[i])
				        del grouping[i]
				if len(text_group) > 0:
					outfile.write("\'"+compare_element.htid+"\',\'"+compare_element.title+"\',\'"+compare_element.author+"\',\'"+str(compare_element.K)+"\',\'"+compare_element.imprint+"\',\'"+compare_element.enumcron+"\',\'"+str(compare_element.totalpages)+"\'\n")
					for found in text_group:
						outfile.write("\'"+found.htid+"\',\'"+found.title+"\',\'"+found.author+"\',\'"+str(found.K)+"\',\'"+found.imprint+"\',\'"+found.enumcron+"\',\'"+str(found.totalpages)+"\'\n")
					outfile.write("\n")


	end = timer()
	print end - start
开发者ID:messner1,项目名称:htrc-yule,代码行数:29,代码来源:remove_repetitions.py


示例20: import_images

def import_images(folder, par=True, ttime=True):
  """
  This function loads images from a folder as PIL Image files and
  thresholds them, creating a list of z-slices to be turned into a matrix
  This version is not currently used.
  """
  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)
  newtiflist = [folder+f for f in tiflist].sort() # alphabetize
  tifobjs = [load_img_array(f) for f in tiflist]
  
  # here start parallel stuff
  if par or ttime:
    start_time_par = timer()
    pool = Pool(8)
    results_par = pool.map(show_at_thresh, tifobjs)
    pool.close()
    pool.join()
    total_time_par = timer() - start_time_par
  # or non-parallel stuff
  elif par==False or ttime:
    start_time_nopar = timer()
    results_nopar = [show_at_thresh(f) for f in newtiflist]
    total_time_nopar = timer() - start_time_nopar
  print('Time for parallel: %.2f seconds' % total_time_par)
  print('Time for non-parallel: %.2f seconds' % total_time_nopar)
  
  return results_par, results_nopar
开发者ID:mlabadi2,项目名称:code,代码行数:35,代码来源:imageMatrix.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python timeit.Timer类代码示例发布时间:2022-05-27
下一篇:
Python timeit.timeit函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap