def can_solve(args): if len(args) != 2: print("To use, submit the number of a problem to run:\n\n$ python project_euler 111\n") print(all_problems()) return try: problem_number = int(args[1]) except ValueError: print("Problem number must be an int") return pattern = re.compile(r"^(solved|problems)\.p{:d}$".format(problem_number)) for module_name, module in sys.modules.items(): match = pattern.match(module_name) if match: if match.group(1) == "solved": solution = module.main() print("Solution to problem {:d}: {:s}\n\nBenchmarking...\n".format( problem_number, str(solution))) timeit.main(args=shlex.split("-s'from {:s} import main' 'main()'".format(module_name))) return else: print("Problem {:d} in progress. Current output:".format(problem_number)) print(module.main()) return print("Cannot find problem {:d}\n{:s}".format(problem_number, all_problems()))
def timefunc(func, n=3, mod=''): """Run func in timeit.main, n times, import from mod, mod defaults to name of the func.""" parpos=func.find('(') if parpos == -1: print "You need to specify arguments or at least parentheses after the name of the function" return -1 funcname=func[0:parpos] if mod=='': mod=funcname timeit.main(['-s', 'from ' + mod + ' import ' + funcname, '-n', n, func])
def run_main(self, seconds_per_increment=1.0, switches=None, timer=None): if timer is None: timer = FakeTimer(seconds_per_increment=seconds_per_increment) if switches is None: args = [] else: args = switches[:] args.append(self.fake_stmt) orig_sys_path = sys.path[:] with captured_stdout() as s: timeit.main(args=args, _wrap_timer=timer.wrap_timer) sys.path[:] = orig_sys_path[:] return s.getvalue()
def time_functions(module_dict): """ Time all functions in module_dict. Uses timeit to do the timing and writes the results to stdout. """ functions = sorted(find_functions(module_dict).iterkeys()) for name in functions: print('Timing function %s():' % name) timeit.main( args=['-s', 'from __main__ import %s' % name, '%s()' % name]) print('')
def time_executions_A(uncut=False): """ Time executions via timeit module level calls """ for strname in ['SHORT_UNICODE', 'LONG_UNICODE']: # only unicode strings for truncate in truncate_funcs: cut_txt = "UNCUT" if uncut else "CUT at len-2" cut_len = sys.maxsize if uncut else len(TESTSTRS[strname]) - 2 print( f"Time '{truncate.__name__}' with {strname} string {cut_txt}") stmt = ( f"tt.{truncate.__name__}(tt.TESTSTRS['{strname}'], {cut_len})") timeit.main( ['-u', 'usec', '-n', '100000', '-s', TIMEIT_SETUP, stmt])
def run_main(self, seconds_per_increment=1.0, switches=None, timer=None): if timer is None: timer = FakeTimer(seconds_per_increment=seconds_per_increment) if switches is None: args = [] else: args = switches[:] args.append(self.fake_stmt) # timeit.main() modifies sys.path, so save and restore it. orig_sys_path = sys.path[:] with captured_stdout() as s: timeit.main(args=args, _wrap_timer=timer.wrap_timer) sys.path[:] = orig_sys_path[:] return s.getvalue()
def timeit(*args): "Run the timeit.main function with args, catch and parse the output." import sys import re import timeit import cStringIO prev_stdout = sys.stdout sys.stdout = cStringIO.StringIO() timeit.main(args) out = sys.stdout.getvalue() sys.stdout = prev_stdout # Parse the output, and apply our own formatting match = re.search(r"(\d+\.\d*|\d+) usec", out) time = float(match.group(1)) print "%8.2f us: %s" % (time, args[-1])
def _inner(*args, **kwargs): start_record(socks) results = func(*args, **kwargs) def tmp(): start_replay(socks) func(*args, **kwargs) pr = cProfile.Profile() pr.enable() for i in xrange(1000): tmp() pr.disable() pstats.Stats(pr).sort_stats('time').print_stats() # timeit globals()['__tmp'] = tmp timeit.main( ['-s', 'from __main__ import __tmp', '-n', '1000', '__tmp()']) return results
def main(): print "unidecode_expect_ascii, ASCII string" timeit.main([ '-s', 'from unidecode import unidecode_expect_ascii', 'unidecode_expect_ascii(u"Hello, World")' ]) print "unidecode_expect_ascii, non-ASCII string" timeit.main([ '-s', 'from unidecode import unidecode_expect_ascii', 'unidecode_expect_ascii(u"¡Hola mundo!")' ]) print "unidecode_expect_nonascii, ASCII string" timeit.main([ '-s', 'from unidecode import unidecode_expect_nonascii', 'unidecode_expect_nonascii(u"Hello, World")' ]) print "unidecode_expect_nonascii, non-ASCII string" timeit.main([ '-s', 'from unidecode import unidecode_expect_nonascii', 'unidecode_expect_nonascii(u"¡Hola mundo!")' ])
def main(): print "unidecode_expect_ascii, ASCII string" timeit.main([ '-s', 'from unidecode import unidecode_expect_ascii', 'unidecode_expect_ascii(u"Hello, World")']) print "unidecode_expect_ascii, non-ASCII string" timeit.main([ '-s', 'from unidecode import unidecode_expect_ascii', 'unidecode_expect_ascii(u"¡Hola mundo!")']) print "unidecode_expect_nonascii, ASCII string" timeit.main([ '-s', 'from unidecode import unidecode_expect_nonascii', 'unidecode_expect_nonascii(u"Hello, World")']) print "unidecode_expect_nonascii, non-ASCII string" timeit.main([ '-s', 'from unidecode import unidecode_expect_nonascii', 'unidecode_expect_nonascii(u"¡Hola mundo!")'])
def run(self): self.setup_path() from timeit import main #t = timeit(setup="import ed25519", stmt="ed25519.create_keypair()", number=1000) sys.stdout.write(" keypair generation") main(["-n", "1000", "-s", "import ed25519", "ed25519.create_keypair()"]) sys.stdout.write(" signing:") main(["-n", "1000", "-s", "import ed25519; sk,vk=ed25519.create_keypair(); msg=b'hello world'", "sk.sign(msg)"]) sys.stdout.write(" verifying:") main(["-n", "1000", "-s", "import ed25519; sk,vk=ed25519.create_keypair(); msg=b'hello world'; sig=sk.sign(msg)", "vk.verify(sig,msg)"])
def get_random_string2(count): allowed_chars = 'abcdefghijklmnopqrstuvwxyz0123456789' l = [] for i in range(count): l.append(random.choice(allowed_chars)) return ''.join(l) def test(): for i in range(100): print get_random_string2(12) print get_rand_string(12) test() import timeit timeit.main([ '-s', 'from __main__ import get_rand_string', '-n', '10000', 'get_rand_string(12)' ]) timeit.main([ '-s', 'from __main__ import get_random_string', '-n', '10000', 'get_random_string(12)' ]) timeit.main([ '-s', 'from __main__ import get_random_string2', '-n', '10000', 'get_random_string2(12)' ])
def bench(): 'the operation for benchmark' rds.set('test', 100) def run_with_recording(sock, func): sock.start_record() func() def run_with_replay(sock, func): sock.start_replay() func() # record once run_with_recording(pool.conn._sock, bench) import timeit timeit.main([ '-s', 'from __main__ import run_with_replay, pool, bench', '-n', '10000', 'run_with_replay(pool.conn._sock, bench)' ]) import cProfile if sys.version_info[0] >= 3: xrange = range cProfile.run('for i in xrange(10000):run_with_replay(pool.conn._sock, bench)', sort='time')
rp = RawPlayer() p = Player() cp = CPlayer() def set_and_get(p): #p.userID = 1 #return p.userID return p.formula3 if __name__ == '__main__': import timeit, cProfile timeit.main([ '-s', 'from __main__ import set_and_get, rp', '-n', '10000', 'set_and_get(rp)' ]) timeit.main([ '-s', 'from __main__ import set_and_get, p', '-n', '10000', 'set_and_get(p)' ]) timeit.main([ '-s', 'from __main__ import set_and_get, cp', '-n', '10000', 'set_and_get(cp)' ]) cProfile.run('for i in xrange(10000): set_and_get(cp)', sort='time') cProfile.run('for i in xrange(10000): set_and_get(p)', sort='time')
def test_insert(): x = [] for i in range(10000): x.insert(0, i) return x def benchmark(function, number=100, repeat=10): # Measure the execution times times = timeit.repeat(function, number=number, globals=globals()) # The repeat function gives `repeat` results so we take the min() # and divide it by the number of runs time = min(times) / number print('%d loops, best of %d: %9.6fs :: %s' % ( number, repeat, time, function)) if __name__ == '__main__': benchmark('test_list()') benchmark('test_list_comprehension()') benchmark('test_append()') benchmark('test_insert()') ############################################################################## import timeit timeit.main(args=['[x for x in range(1000000)]'])
pool.conn.connect() rds = redis.StrictRedis(connection_pool=pool) def bench(): 'the operation for benchmark' rds.set('test', 100) def run_with_recording(sock, func): sock.start_record() func() def run_with_replay(sock, func): sock.start_replay() func() # record once run_with_recording(pool.conn._sock, bench) import timeit timeit.main(['-s', 'from __main__ import run_with_replay, pool, bench', '-n', '10000', 'run_with_replay(pool.conn._sock, bench)']) import cProfile if sys.version_info[0] >= 3: xrange = range cProfile.run('for i in xrange(10000):run_with_replay(pool.conn._sock, bench)', sort='time')
def f(): pass def shallow(n): for x in range(n): f() def deep(n): if n != 0: deep(n - 1) if __name__ == '__main__': try: func_name = sys.argv[1] except IndexError: print('Usage: python subcalls_example.py shallow|deep [100]') raise SystemExit(1) try: n = int(sys.argv[2]) except IndexError: n = 100 timeit.main([ '-s', 'from subcalls_example ' 'import %s as f' % func_name, 'f(%d)' % n ])
rds.set("test", 100) def bench_pipeline(): pipe = rds.pipeline() pipe.set(1, 1) pipe.incr(1) pipe.incrby(1, 1) pipe.get(1) pipe.execute() bench = bench_pipeline # record once run_with_recording(pool.conn._sock, bench) timeit.main([ "-s", "from __main__ import run_with_replay, pool, bench", "-n", "10000", "run_with_replay(pool.conn._sock, bench)", ]) if sys.version_info[0] >= 3: xrange = range cProfile.run("for i in xrange(10000):run_with_replay(pool.conn._sock, bench)", sort="time")
class TestPrimes(unittest.TestCase): LIMIT = 1000 def is_prime(self, it): """naive prime test, to avoid logic errors""" return it > 0 \ and (it == 2 or it % 2 != 0) \ and (it == 1 or not (any(it % number == 0 for number in range(3, it // 2, 2)))) def test_generated_numbers_are_prime(self): for maybe_prime in itertools.islice(primes(), 0, TestPrimes.LIMIT): self.assertTrue(self.is_prime(maybe_prime), "%d is not a prime" % maybe_prime) class TestFactorize(unittest.TestCase): PRIMES = list(itertools.islice(primes(), 0, 1000)) @given(lists(elements=sampled_from(PRIMES), min_size=1, max_size=40, average_size=20)) def test_finds_constituent_prime_factors(self, factors): number = 1 for f in factors: number *= f self.assertEqual(Counter(factors), Counter(factorize(number))) if __name__ == '__main__': timeit.main(['--setup', 'from __main__ import factorize', 'factorize(123456789)']) unittest.main()
try: pass except: pass try: pass except: pass try: pass except: pass try: pass except: pass def calibrate(self): for i in xrange(self.rounds): pass ### Test to make Fredrik happy... if __name__ == '__main__': import timeit timeit.TestClass = TryRaiseExcept timeit.main( ['-s', 'test = TestClass(); test.rounds = 1000', 'test.test()'])
def bench_pipeline(): rds.execute_pipeline( ("SET", 1, 1), ("INCR", 1), ("INCRBY", 1, 1), ("GET", 1), ) bench = bench_pipeline # record once patch_socket.run_with_recording(rds._sock, bench) timeit.main([ "-s", "from __main__ import patch_socket, rds, bench", "-n", "10000", "patch_socket.run_with_replay(rds._sock, bench)", ]) if sys.version_info[0] >= 3: xrange = range cProfile.run( "for i in xrange(10000):patch_socket.run_with_replay(rds._sock, bench)", sort="time")
def update_event(self, inp=-1): self.set_output_val(0, timeit.main(self.input(0)))
h = Harness() if __name__ == "__main__": if len(sys.argv) == 1: all_params = ["params_80", "params_112", "params_128"] all_names = ["construct", "one", "two", "three"] else: params, name = sys.argv[1].split(".") all_params = [params] all_names = [name] for params in all_params: for name in all_names: print "%s %s:" % (params, name), timeit.main([ "--setup", ("import bench_jpake; " "bench_jpake.h.setup(bench_jpake.%s)" % params), "bench_jpake.h.%s()" % name, ]) # % python jpake/bench_jpake.py # params_80 construct: 100000 loops, best of 3: 14.9 usec per loop # params_80 one: 10 loops, best of 3: 38.9 msec per loop # params_80 two: 10 loops, best of 3: 66.3 msec per loop # params_80 three: 10 loops, best of 3: 48.1 msec per loop # params_112 construct: 100000 loops, best of 3: 14.6 usec per loop # params_112 one: 10 loops, best of 3: 184 msec per loop # params_112 two: 10 loops, best of 3: 295 msec per loop # params_112 three: 10 loops, best of 3: 219 msec per loop # params_128 construct: 100000 loops, best of 3: 13.5 usec per loop # params_128 one: 10 loops, best of 3: 424 msec per loop # params_128 two: 10 loops, best of 3: 659 msec per loop
rds = credis.Connection() rds.connect() def bench_simple(): 'the operation for benchmark' rds.execute('SET', 'test', 100) def bench_pipeline(): rds.execute_pipeline( ('SET', 1, 1), ('INCR', 1), ('INCRBY', 1, 1), ('GET', 1), ) bench = bench_pipeline # record once patch_socket.run_with_recording(rds._sock, bench) timeit.main(['-s', 'from __main__ import patch_socket, rds, bench', '-n', '10000', 'patch_socket.run_with_replay(rds._sock, bench)']) if sys.version_info[0] >= 3: xrange = range cProfile.run('for i in xrange(10000):patch_socket.run_with_replay(rds._sock, bench)', sort='time')
from __future__ import with_statement import timeit setup = """ import pprint import prettyprinter as pp from format import format, parse_control_string null = open("/dev/null", "w") tupler = "(~{~A,~^ ~@{~A~^, ~}~})" l = tuple(xrange(1000)) d = dict(zip(range(100), range(100, 200))) """[1:] stmts = (("parse", """tuple(parse_control_string(tupler))"""), ("format", """format(null, "~~foo: ~D pon~:@P~%", 3)"""), ("iteration", """format(null, tupler, l)"""), ("prettyprinter", """pp.pprint(l, stream=null)"""), ("pprint", """pprint.pprint(l, null)""")) for name, stmt in stmts: print ">> %s" % name timeit.main(["-s", setup, stmt]) print
differences.append(b-a) a = b return differences def difs_imap(seq): return imap(sub, seq[1:], seq[:-1]) _sub = lambda seq: lambda i: seq[i+1] - seq[i] def difs_xrange(seq): sub = _sub(seq) return imap(sub,xrange(len(seq)-1)) #print list(difs_izip(range(100))) #print list(difs_xrange(range(100))) == list(difs_izip(range(100))) if __name__ == '__main__': import psyco; psyco.full() import timeit funs = 'wib izip imap xrange '.split() #loop zip reduce test = lambda f: list(f(range(999))) assert reduce(and_, [test(difs_wib) == test(f) for f in difs_izip,difs_xrange,difs_imap, difs_loop, difs_zip, difs_reduce]) bargs = ['-c', '-simport loop_bench', '-sx=range(100)'] #'-sx=[bench.Point(1,2)]*1000'] #funs = 'izip map'.split() for fun in funs: args = bargs + ['loop_bench.difs_%s(x)' % fun] print '%8s:' % fun, timeit.main(args)
import timeit def f(): pass def shallow(n): for x in range(n): f() def deep(n): if n != 0: deep(n - 1) if __name__ == '__main__': try: func_name = sys.argv[1] except IndexError: print('Usage: python subcalls_example.py shallow|deep [100]') raise SystemExit(1) try: n = int(sys.argv[2]) except IndexError: n = 100 timeit.main(['-s', 'from subcalls_example ' 'import %s as f' % func_name, 'f(%d)' % n])
l = [] for i in range(1000): l = l + [i] def method2(): l = [] for i in range(1000): l.append(i) def method3(): l = [n for n in range(1000)] def method4(): l = list(range(1000)) ''' 10000000 loops, best of 5: 13.9 nsec per loop 10000000 loops, best of 5: 12 nsec per loop 10000000 loops, best of 5: 11.3 nsec per loop 10000000 loops, best of 5: 11.5 nsec per loop ''' if __name__ == '__main__': timeit.main(method1()) timeit.main(method2()) timeit.main(method3()) timeit.main(method4())
import timeit setup = 'import cv2; import numpy as np; hsv = cv2.cvtColor(cv2.imread("img.png"), cv2.COLOR_BGR2HSV)' timeit.main(['-s', setup, 'hue, saturation, value = hsv[:, :, 0], hsv[:, :, 1], hsv[:, :, 2]']) timeit.main(['-s', setup, 'hue, saturation, value = map(np.squeeze, np.dsplit(hsv, 3))']) timeit.main(['-s', setup, 'hue, saturation, value = map(np.squeeze, np.split(hsv, 3, axis=2))']) timeit.main(['-s', setup, 'hue, saturation, value = cv2.split(hsv)'])
pass try: pass except: pass try: pass except: pass try: pass except: pass try: pass except: pass def calibrate(self): for i in xrange(self.rounds): pass ### Test to make Fredrik happy... if __name__ == '__main__': import timeit timeit.TestClass = TryRaiseExcept timeit.main(['-s', 'test = TestClass(); test.rounds = 1000', 'test.test()'])
def bench_simple(): 'the operation for benchmark' rds.execute('SET', 'test', 100) def bench_pipeline(): rds.execute_pipeline( ('SET', 1, 1), ('INCR', 1), ('INCRBY', 1, 1), ('GET', 1), ) bench = bench_pipeline # record once patch_socket.run_with_recording(rds._sock, bench) timeit.main([ '-s', 'from __main__ import patch_socket, rds, bench', '-n', '10000', 'patch_socket.run_with_replay(rds._sock, bench)' ]) if sys.version_info[0] >= 3: xrange = range cProfile.run( 'for i in xrange(10000):patch_socket.run_with_replay(rds._sock, bench)', sort='time')
settings.watch() from common import ConfigFiles from config.configs import get_registereds from yy.config.fields import ValidationError config_files = ConfigFiles(settings.REGION['ID']) try: config_files.load_configs(get_registereds(), settings.CONFIG_FILE_PATH) except ValidationError as e: print e.message.encode("utf-8") raise e from player.model import Player p = Player.load(11) print p.name from task.manager import on_end_fb_count, on_levelup import timeit import cProfile timeit.main( ['-s', 'from __main__ import on_levelup, p', '-n', '1', 'on_levelup(p)']) cProfile.run('for i in xrange(1):on_levelup(p)', sort='time') #timeit.main(['-s', 'from __main__ import on_end_fb_count, p', # '-n', '1000', 'on_end_fb_count(p, 100111)']) # #cProfile.run('for i in xrange(1000):on_end_fb_count(p, 100111)', # sort='time')
h = Harness() if __name__ == "__main__": if len(sys.argv) == 1: all_params = ["params_80", "params_112", "params_128"] all_names = ["construct", "one", "two", "three"] else: params,name = sys.argv[1].split(".") all_params = [params] all_names = [name] for params in all_params: for name in all_names: print "%s %s:" % (params, name), timeit.main(["--setup", ("import bench_jpake; " "bench_jpake.h.setup(bench_jpake.%s)" % params), "bench_jpake.h.%s()" % name, ]) # % python jpake/bench_jpake.py # params_80 construct: 100000 loops, best of 3: 14.9 usec per loop # params_80 one: 10 loops, best of 3: 38.9 msec per loop # params_80 two: 10 loops, best of 3: 66.3 msec per loop # params_80 three: 10 loops, best of 3: 48.1 msec per loop # params_112 construct: 100000 loops, best of 3: 14.6 usec per loop # params_112 one: 10 loops, best of 3: 184 msec per loop # params_112 two: 10 loops, best of 3: 295 msec per loop # params_112 three: 10 loops, best of 3: 219 msec per loop # params_128 construct: 100000 loops, best of 3: 13.5 usec per loop # params_128 one: 10 loops, best of 3: 424 msec per loop # params_128 two: 10 loops, best of 3: 659 msec per loop