我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用timeit.timeit()。
def tearDown(self): if self.src_before and self.optimizations: if not isinstance(self.src_before, (list, tuple)): self.src_before = (self.src_before, ) if not isinstance(self.optimizations, (list, tuple)): self.optimizations = (self.optimizations, ) for src_before in self.src_before: src_after = src_before for optimization in self.optimizations: src_after = self.optimize(src_after, optimization) self.time_before += timeit(src_before, setup=self.set_up) self.time_after += timeit(src_after , setup=self.set_up) self.assertGreaterEqual(self.time_before, self.time_after) self.time_before = 0 self.time_after = 0 self.src_before = () self.optimizations = () self.set_up = None
def get_env(ctx): return dict( print=print_, timeit=timeit, dis=dis, discord=discord, bot=ctx.bot, client=ctx.bot, ctx=ctx, con=ctx.con, msg=ctx.message, message=ctx.message, guild=ctx.guild, server=ctx.guild, channel=ctx.channel, me=ctx.me )
def plot(): ''' ''' # Register the functions builtins.__dict__.update(globals()) # Loop over various dataset sizes Narr = np.logspace(0, 5, 5) tpp = np.zeros_like(Narr) tbm = np.zeros_like(Narr) tps = np.zeros_like(Narr) for i, N in enumerate(Narr): tpp[i] = timeit.timeit('run_pp(%d)' % N, number = 10) / 10. if batman is not None: tbm[i] = timeit.timeit('run_bm(%d)' % N, number = 10) / 10. if ps is not None: tps[i] = timeit.timeit('run_ps(%d)' % N, number = 10) / 10. pl.plot(Narr, tpp, '-o', label = 'planetplanet') if batman is not None: pl.plot(Narr, tbm, '-o', label = 'batman') if ps is not None: pl.plot(Narr, tps, '-o', label = 'pysyzygy') pl.legend() pl.yscale('log') pl.xscale('log') pl.ylabel('Time [seconds]', fontweight = 'bold') pl.xlabel('Number of datapoints', fontweight = 'bold')
def bench(func, iterations, stat_memory): gc.collect() heap_diff = None if heapy and stat_memory: heap_before = heapy.heap() total_sec = timeit.timeit(func, setup=gc.enable, number=iterations) if heapy and stat_memory: heap_diff = heapy.heap() - heap_before sec_per_req = Decimal(str(total_sec)) / Decimal(str(iterations)) sys.stdout.write('.') sys.stdout.flush() return (sec_per_req, heap_diff)
def determine_iterations(func): # NOTE(kgriffs): Algorithm adapted from IPython's magic timeit # function to determine iterations so that 0.2 <= total time < 2.0 iterations = ITER_DETECTION_MULTIPLIER for __ in range(1, ITER_DETECTION_MAX_ATTEMPTS): gc.collect() total_sec = timeit.timeit( func, setup=gc.enable, number=int(iterations) ) if total_sec >= ITER_DETECTION_DURATION_MIN: assert total_sec < ITER_DETECTION_DURATION_MAX break iterations *= ITER_DETECTION_MULTIPLIER return int(iterations)
def timeit(self, stmt, setup, number=None): self.fake_timer = FakeTimer() t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer) kwargs = {} if number is None: number = DEFAULT_NUMBER else: kwargs['number'] = number delta_time = t.timeit(**kwargs) self.assertEqual(self.fake_timer.setup_calls, 1) self.assertEqual(self.fake_timer.count, number) self.assertEqual(delta_time, number) # Takes too long to run in debug build. #def test_timeit_default_iters(self): # self.timeit(self.fake_stmt, self.fake_setup)
def repeat(self, stmt, setup, repeat=None, number=None): self.fake_timer = FakeTimer() t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer) kwargs = {} if repeat is None: repeat = DEFAULT_REPEAT else: kwargs['repeat'] = repeat if number is None: number = DEFAULT_NUMBER else: kwargs['number'] = number delta_times = t.repeat(**kwargs) self.assertEqual(self.fake_timer.setup_calls, repeat) self.assertEqual(self.fake_timer.count, repeat * number) self.assertEqual(delta_times, repeat * [float(number)]) # Takes too long to run in debug build. #def test_repeat_default(self): # self.repeat(self.fake_stmt, self.fake_setup)
def test_perf(): print('[+] NAS MO decoding and re-encoding') Ta = timeit(test_nas_mo, number=14) print('test_nas_mo: {0:.4f}'.format(Ta)) print('[+] NAS MT decoding and re-encoding') Tb = timeit(test_nas_mt, number=24) print('test_nas_mt: {0:.4f}'.format(Tb)) print('[+] SIGTRAN decoding and re-encoding') Tc = timeit(test_sigtran, number=300) print('test_sigtran: {0:.4f}'.format(Tc)) print('[+] SCCP decoding and re-encoding') Td = timeit(test_sccp, number=100) print('test_sccp: {0:.4f}'.format(Td)) print('[+] mobile total time: {0:.4f}'.format(Ta+Tb+Tc+Td))
def run_timeit(func_1, func_2, num=1): """Run timeit.timeit for the given function names (input args) .. todo:: Make this function robust by handling errors due to incorrect function names. .. todo:: You could also refactor this function and pass the whole function as an argument. Then you can extract the function name string as function.__name__ """ t1 = timeit.timeit("%s()"%func_1, setup="from __main__ import %s"%func_1, number=num) t2 = timeit.timeit("%s()"%func_2, setup="from __main__ import %s"%func_2, number=num) print("Function: {func}, time: {t}".format(func=func_1, t=t1)) print("Function: {func}, time: {t}".format(func=func_2, t=t2)) print("~"*40)
def test_kmax_pooling_time(): nbatches, nkernels_in, nwords, ndim = 50, 16, 58, 300 input_shape = (nbatches, nkernels_in, nwords, ndim) input = T.tensor4('input') k = 1 f_kmax_argsort = theano.function([input], k_max_pooling(input, k)) f_kmax_unroll = theano.function([input], _k_max_pooling(input, k)) f_max = theano.function([input], max_pooling(input)) image_data = np.random.randn(*input_shape).astype(dtype=np.float64) # np.random.shuffle(image_data) image_data = image_data.reshape(input_shape) # print image_data # print 'kmax' print 'f_kmax_argsort', timeit.timeit(lambda: f_kmax_argsort(image_data), number=10) print 'f_kmax_unroll', timeit.timeit(lambda: f_kmax_unroll(image_data), number=10) print 'f_max', timeit.timeit(lambda: f_max(image_data), number=10)
def test_performance_cache(self): """Compare the naive vanilla python lazy property (where property is written in C in the python stdlib) with our IRP lazy_property with the genealogy overhead Python 2.*: 1.25x Python 3.*: 1.75x """ import timeit i = timeit.timeit('f.b0;', setup='from __main__ import BigTree; f = BigTree()', number=5000000) h = timeit.timeit('f.b0_vlp;', setup='from __main__ import BigTree; f = BigTree()', number=5000000) try: self.assertTrue(i < h*1.75) except AssertionError as e: raise e
def factorial(): simple = timeit.timeit('fact_s(52)', ''' from ch03_r07 import fact_s ''') optimized = timeit.timeit('fact_o(52)', ''' from ch03_r07 import fact_o ''') while_statement = timeit.timeit('fact_w(52)', ''' from ch03_r07 import fact_w ''' ) print( "Simple {simple:.4f}".format_map(vars())) print( "Optimized {optimized:.4f}".format_map(vars())) print( "While {while_statement:.4f}".format_map(vars()))
def test_array_vs_getter(self): setup = '''data = ['a'] * 100\n''' setup += '''def get(n):\n''' setup += ''' return data[n]\n''' setup += '''class B:\n''' setup += ''' def __getitem__(self, n):\n''' setup += ''' return data[n]\n''' setup += '''b = B()\n''' a = timeit( '''x = data[5]\n''', setup=setup, number=10000) b = timeit( '''x = get(5)\n''', setup=setup, number=10000) c = timeit( '''x = b[5]\n''', setup=setup, number=10000) #print "\n%s %s %s | %s %s" % (a, b, a/b, c, a/c) # Calling a function or member is significantly slower than direct access. self.assertGreater(b, a * 1.7) self.assertGreater(c, a * 2)
def test_slice_vs_startswith(self): setup = '''x = 'a' * 100\n''' a = timeit( '''x[:2] == " "\n''', setup=setup, number=100000) b = timeit( '''x.startswith(" ")\n''', setup=setup, number=100000) c = timeit( '''x[0] == " " and x[1] == " "\n''', setup=setup, number=100000) #print "\na %s, b %s, c %s | %s %s" % (a, b, c, c, a/c) # Calling a function or member is significantly slower than direct access. self.assertGreater(b, a * 2.0) # b is much slower. self.assertGreater(b, c * 2.0) # b is much slower. self.assertGreater(a, c * 0.7) # a and c are similar. self.assertGreater(c, a * 0.7) # a and c are similar.
def test_default_parameter(self): setup = '''def withDefault(a, b=None):\n''' setup += ''' if b is not None: return b\n''' setup += ''' return a*a\n''' setup += '''def withoutDefault(a, b):\n''' setup += ''' if b is -1: return b\n''' setup += ''' return a*b\n''' a = timeit( '''withDefault(5);''' * 100, setup=setup, number=10000) b = timeit( '''withoutDefault(5, 0);''' * 100, setup=setup, number=10000) # Assert that neither too much faster than the other self.assertGreater(a, b * 0.81) self.assertGreater(b, a * 0.77)
def test_split_insert(self): return # Remove to enable test (disabled due to running time). # This tests a performance assumption. If this test fails, the program # should still work fine, but it may not run as fast as it could by using # different assumptions. # # With frequent splitting the performance reverses. for lineCount in (100, 1000, 5000): half = lineCount / 2 a = timeit(r'''data2 = data1.split('\n'); \ data2[%s] = data2[%s][:50] + "x" + data2[%s][50:]; \ ''' % (half, half, half), setup=r'''data1 = ("a" * 100 + '\n') * %s''' % (lineCount,), number=10000) b = timeit('data1 = data1[:%s] + "x" + data1[%s:]' % (half, half), setup=r'''data1 = ("a" * 100 + '\n') * %s''' % (lineCount,), number=10000) print "\n%9s: %s %s" % (lineCount, a, b) self.assertGreater(a, b)
def permscan(self, address_space, offset = 0, maxlen = None): times = [] # Run a warm-up scan to ensure the file is cached as much as possible self.oldscan(address_space, offset, maxlen) perms = list(itertools.permutations(self.checks)) for i in range(len(perms)): self.checks = perms[i] print "Running scan {0}/{1}...".format(i + 1, len(perms)) profobj = ScanProfInstance(self.oldscan, address_space, offset, maxlen) value = timeit.timeit(profobj, number = self.repeats) times.append((value, len(list(profobj.results)), i)) print "Scan results" print "{0:20} | {1:7} | {2:6} | {3}".format("Time", "Results", "Perm #", "Ordering") for val, l, ordering in sorted(times): print "{0:20} | {1:7} | {2:6} | {3}".format(val, l, ordering, perms[ordering]) sys.exit(1)
def libsnmp_encode_decode(): try: import libsnmp.rfc1905 as libsnmp_rfc1905 def decode(): libsnmp_rfc1905.Message().decode(ENCODED_MESSAGE) encode_time = float('inf') decode_time = timeit.timeit(decode, number=ITERATIONS) except ImportError: encode_time = float('inf') decode_time = float('inf') print('Unable to import libsnmp.') except SyntaxError: encode_time = float('inf') decode_time = float('inf') print('Syntax error in libsnmp.') return encode_time, decode_time
def pyasn1_encode_decode(): try: from pysnmp.proto import api from pyasn1.codec.ber import decoder snmp_v1 = api.protoModules[api.protoVersion1].Message() def decode(): decoder.decode(ENCODED_MESSAGE, asn1Spec=snmp_v1) encode_time = float('inf') decode_time = timeit.timeit(decode, number=ITERATIONS) except ImportError: encode_time = float('inf') decode_time = float('inf') print('Unable to import pyasn1.') return encode_time, decode_time
def test_benchmark(self): """Benchmark our code against a regex baseline.""" baseline_speed = timeit.timeit( "baseline.split(testcase)", setup=TEST_SETUP, number=self.bench_iterations, ) cypunct_speed = timeit.timeit( "cypunct.split(testcase)", setup=TEST_SETUP, number=self.bench_iterations, ) print( "\nBenchmark results: ({0} loops)\n\n".format( self.bench_iterations)) print("baseline speed:", baseline_speed, sep="\t") print("cypunct speed:", cypunct_speed, sep="\t")
def easy_timer(code_to_benchmark, *, repeat=3, number=1000): """ Wrap timeit.Timer().repeat() to catch locals. Rather than put our setup statement in a string for :py:func:`timeit.timeit`, we can just pull locals and globals from the calling stack frame. Args: code_to_benchmark(str): A string containing the Python code that we want to benchmark. repeat(int): Number of times to repeat the timer trial. number(int): Number of iterations **per** trial. Returns: (float): The best measured time of ``repeat`` times. """ timer = timeit.Timer(stmt=code_to_benchmark, globals=copy_environment(2)) best_time = min(timer.repeat(repeat=repeat, number=number)) return best_time
def print_easy_timer(code_to_benchmark, *, repeat=3, number=1000): """ Repeatedly time code and print results. Args: code_to_benchmark(str): A string containing the Python code that we want to benchmark. repeat(int): Number of times to repeat the timer trial. number(int): Number of iterations **per** trial. Returns: (float): The best measured time of ``repeat`` times. """ timer = timeit.Timer(stmt=code_to_benchmark, globals=copy_environment(2)) best_time = min(timer.repeat(repeat=repeat, number=number)) print(":\t\t".join(( code_to_benchmark, str(best_time) ))) return best_time
def run(frameworks, number, do_profile): print("Benchmarking frameworks:", ', '.join(frameworks)) sys.path[0] = '.' path = os.getcwd() print(" ms rps tcalls funcs") for framework in frameworks: os.chdir(os.path.join(path, framework)) try: main = __import__('app', None, None, ['main']).main f = lambda: list(main(environ.copy(), start_response)) time = timeit(f, number=number) st = Stats(profile.Profile().runctx( 'f()', globals(), locals())) print("%-11s %6.0f %7.0f %7d %6d" % (framework, 1000 * time, number / time, st.total_calls, len(st.stats))) if do_profile: st = Stats(profile.Profile().runctx( 'timeit(f, number=number)', globals(), locals())) st.strip_dirs().sort_stats('time').print_stats(10) del sys.modules['app'] except ImportError: print("%-15s not installed" % framework)
def measure_time(self): logger = init_logger("measure_time") logger.info("Begin measure time") loaded_module = SourceFileLoader( self.module_name, self.path_to_module).load_module() all_functions = inspect.getmembers(loaded_module, inspect.isfunction) fun_names = [] for i in all_functions: fun_names.append(i[0]) if self.function_to_measure.split("(")[0] not in fun_names: logger.info("ArgFunNameError raised because " "of no function with this name") logger.debug(self.function_to_measure.split("(")[0]) logger.debug(all_functions) raise ArgFunNameError returns_values_list = [] init_struct_code_copy = self.init_struct_code for i in range(0, self.repeats): setup = "from {0} import {1}; {2}"\ .format(self.module_name, self.function_to_measure.split("(")[0], init_struct_code_copy) @exit_after(self.timeout) def __inside_measure(): returns_values_list.append( timeit.timeit(self.function_to_measure, setup=setup, number=1)) __inside_measure() logger.debug(init_struct_code_copy) logger.info("Times loop: " + str(i)) init_struct_code_copy = add_step(init_struct_code_copy, self.step) logger.info(returns_values_list) logger.info("End measure time") return returns_values_list
def durations(self, reps=1000): """calculate durations for <reps> games""" timing = timeit( setup="from mau_mau.play import play_game;" "from mau_mau.rules import MauMau;" "mmRules = MauMau()", stmt="play_game(mmRules, 3)", number=reps) log.info("it takes %0.3f seconds to play %s games", timing, reps)
def bench_func(func, n=10): """Benchmark the given function.""" return timeit(func, number=n) / n
def my_timeit(): cdeque = """ import collections s = collections.deque() """ t1 = timeit("s.appendleft(37)", cdeque, number=100000) t2 = timeit("s.insert(0, 37)", "s=[]", number=100000) print("t1=", t1) print("t2=", t2) pass
def timeit_usage(): start=time.clock() print timeit.timeit('test_func()','from __main__ import test_func',number=10000) end=time.clock() print end-start
def misc(): vals1 = np.array([1, np.nan, 3, 4]) print vals1.sum() for dtype in ['object', 'int']: print("dtype =", dtype) # print timeit.timeit(np.arange(1E6, dtype=dtype).sum()) start = time.time() print np.arange(1E8, dtype=dtype).sum() print time.time()-start
def main(): l = 2201426263 p = 6 * l - 1 F = ExtendedFiniteField(p, "x^2+x+1") E = EllipticCurve(F, 0, 1) i = 3 while True: y = E.get_corresponding_y(i) if y != None: P = E(i, y) if (l * P).is_infinity(): break i += 1 print(P) rand = [randint(2**31, 2**32) for _ in xrange(10)] count = 20 weil_time = [] print("[+] Weil Pairing: ") for x in rand: r = timeit("bench_pairing.do_test()", setup="import bench_pairing; from ecpy import EllipticCurve, ExtendedFiniteField; bench_pairing.init_test('weil', [%r, %r, %r.distortion_map(), %r])" % (E, P, x*P, l), number=count) weil_time += [r] show_results("weil", r, count) print("[+] Tate Pairing: ") tate_time = [] for x in rand: r = timeit("bench_pairing.do_test()", setup="import bench_pairing; from ecpy import EllipticCurve, ExtendedFiniteField; bench_pairing.init_test('tate', [%r, %r, %r.distortion_map(), %r, 2])" % (E, P, x*P, l), number=count) tate_time += [r] show_results("tate", r, count) print("=" * 64) show_results("weil", sum(weil_time), count * 10) show_results("tate", sum(tate_time), count * 10)
def run_timeit(message_name, message, iterations=ITERATIONS): data = message.encode() def test_encode(): message.encode() def test_decode(): decode(data) encode_time = timeit.timeit(test_encode, number=iterations) decode_time = timeit.timeit(test_decode, number=iterations) print('{}: encode {} decode {}'.format(message_name, encode_time, decode_time))
def benchmark(rdb, sample, refs): """ Basic benchmarking function, call with a reference db `rdb`, a `sample` and a list of `refs`. """ def bench1(): return [compare_strings_concat_levenshtein(sample, ref) for ref in refs] def bench2(): return [compare_strings_set_union(sample, ref) for ref in refs] def bench3(): return [compare_cc_list_levenshtein(sample, ref) for ref in refs] def bench4(): return [compare_cc_list_set_union(sample, ref) for ref in refs] def bench5(): return [compare_cc_spp(sample, ref) for ref in refs] def bench6(): return [compare_bb_hash_bloomfilter(sample, ref) for ref in refs] # Only run the slow ones a few times, and cc3 only once because of caching t1 = timeit.timeit(lambda: bench1(), setup="gc.enable()", number=5) / 5.0 t2 = timeit.timeit(lambda: bench2(), setup="gc.enable()", number=100) / 100.0 t3 = timeit.timeit(lambda: bench3(), setup="gc.enable()", number=100) / 100.0 t4 = timeit.timeit(lambda: bench4(), setup="gc.enable()", number=100) / 100.0 t5 = timeit.timeit(lambda: bench5(), setup="gc.enable()", number=1) / 1.0 t6 = timeit.timeit(lambda: bench6(), setup="gc.enable()", number=100) / 100.0 print(t1, t2, t3, t4, t5, t6)
def main(): global et312 parser = argparse.ArgumentParser() parser.add_argument("-p", "--port", dest="serial_port", help="Serial Port to use") args = parser.parse_args() if not args.serial_port: print("Serial port argument is required!") sys.exit(1) with buttshock.et312.ET312SerialSync(args.serial_port) as et312: et312.perform_handshake() key = et312.key print("Key is {0:#x} ({0})".format(et312.key, et312.key)) current_baud_rate = et312.get_baud_rate() print("Current baud flag: {:#02x}".format(current_baud_rate)) print("Running 1000 mode gets test") # Get the current mode print("Total time: {}", timeit.timeit(stmt=read_mode, number=1000)) print("Shifting baud rate") with buttshock.et312.ET312SerialSync(args.serial_port, key=key, shift_baud_rate=True) as et312: print("Running 1000 mode gets test") print("Total time: {}", timeit.timeit(stmt=read_mode, number=1000))
def __init__(self, seconds_per_increment=1.0): self.count = 0 self.setup_calls = 0 self.seconds_per_increment=seconds_per_increment timeit._fake_timer = self