SHARE
TWEET

Untitled

a guest Aug 25th, 2019 75 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import timeit
  2. from collections import namedtuple
  3. from operator import attrgetter
  4. from contextlib import contextmanager
  5.  
  6. @contextmanager
  7. def start_stop(msg):
  8.     print('*'*10, msg, '*'*10)
  9.     yield
  10.     print('ok')
  11.  
  12.  
  13. def pretty_result(repeat_list_with_seconds):
  14.     cum_time = sum(repeat_list_with_seconds)
  15.     avg = cum_time / repeat / loops
  16.     print('cum_time = {}, avg = {}'.format(cum_time, avg))
  17.  
  18.  
  19. with start_stop('create test data'):
  20.     test = namedtuple('test', 'id')
  21.     container = [test(i) for i in range(100)]
  22.  
  23.  
  24. with start_stop('create cases'):
  25.     loop = """result = {}
  26. for i in container:
  27.    result[i.id] = 1
  28.    """
  29.  
  30.     gen = """ids = map(attrgetter('id'), container)
  31. result = dict.fromkeys(ids, 1)
  32.    """
  33.  
  34.     comp = "{i.id: 1 for i in container}"
  35.  
  36.     setup = 'from __main__ import test, container, attrgetter'
  37.  
  38.  
  39. with start_stop('run tests'):
  40.     loops = 1_000_000
  41.     repeat = 5
  42.  
  43.     with start_stop('gen'):
  44.         time_in_seconds = timeit.repeat(gen, setup=setup, repeat=repeat, number=loops)
  45.         pretty_result(time_in_seconds)
  46.  
  47.     with start_stop('comp'):
  48.         time_in_seconds = timeit.repeat(comp, setup=setup, repeat=repeat, number=loops)
  49.         pretty_result(time_in_seconds)
  50.  
  51.     with start_stop('loop'):
  52.         time_in_seconds = timeit.repeat(loop, setup=setup, repeat=repeat, number=loops)
  53.         pretty_result(time_in_seconds)
  54.  
  55.  
  56. # output
  57.  
  58. $ python3 gen_loop_tests.py
  59. ********** create test data **********
  60. ok
  61. ********** create cases **********
  62. ok
  63. ********** run tests **********
  64. ********** gen **********
  65. cum_time = 64.32173748599962, avg = 1.2864347497199924e-05
  66. ok
  67. ********** comp **********
  68. cum_time = 50.536007013000926, avg = 1.0107201402600186e-05
  69. ok
  70. ********** loop **********
  71. cum_time = 51.675969284999155, avg = 1.0335193856999831e-05
  72. ok
  73. ok
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top