Advertisement
Guest User

`not any` vs `all(genexp)` speed test

a guest
Jun 26th, 2016
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. ''' Compare the speed of `not any` vs `all(genexp)`
  4.  
  5.    See http://stackoverflow.com/a/38024771/4014959\
  6.    http://pastebin.com/rvVBz0Zs
  7.  
  8.    Written by PM 2Ring 2016.06.26
  9. '''
  10.  
  11. from timeit import Timer
  12. import dis
  13.  
  14. count = [0] * 256
  15.  
  16. commands = {
  17.     'any': 'not any(count)',
  18.     'all_genexp': 'all(not c for c in count)',
  19. }
  20.  
  21. def time_test(loops, reps):
  22.     ''' Print timing stats for all the commands '''
  23.     timings = []
  24.     for name, cmd in commands.items():
  25.         setup = 'from __main__ import count'
  26.         t = Timer(cmd, setup)
  27.         result = t.repeat(reps, loops)
  28.         result.sort()
  29.         timings.append((result, name))
  30.  
  31.     timings.sort()
  32.     for result, name in timings:
  33.         print('{:10} {}'.format(name, result))
  34.  
  35.     #Find the ratio of slowest / fastest
  36.     tlo, thi = [timings[i][0][0] for i in (0, -1)]
  37.     print('ratio: {:f}'.format(thi / tlo))
  38.  
  39. def disassemble():
  40.     ''' Show the bytecode of all the commands '''
  41.     for name, cmd in commands.items():
  42.         print(name)
  43.         dis.dis(cmd)
  44.         print()
  45.  
  46. def verify():
  47.     ''' Verify that all commands give the same result '''
  48.     results = [eval(cmd) for cmd in commands.values()]
  49.     #print(results)
  50.     r0 = results[0]
  51.     print(all(r == r0 for r in results[1:]))
  52.  
  53. #disassemble()
  54.  
  55. # Do the tests.
  56. reps = 5
  57. loops = 2000
  58.  
  59. #The first test is with no element of `count` set.
  60. index = None
  61. for _ in range(10):
  62.     print('\nindex = {}, loops = {}'.format(index, loops))
  63.     verify()
  64.     time_test(loops, reps)
  65.  
  66.     if index is None:
  67.         index = len(count) - 1
  68.     else:
  69.         index = (index - 1) // 2
  70.         if index > 7:
  71.             loops *= 2
  72.  
  73.     count[index] = 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement