Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- ''' Compare the speed of `not any` vs `all(genexp)`
- See http://stackoverflow.com/a/38024771/4014959\
- http://pastebin.com/rvVBz0Zs
- Written by PM 2Ring 2016.06.26
- '''
- from timeit import Timer
- import dis
- count = [0] * 256
- commands = {
- 'any': 'not any(count)',
- 'all_genexp': 'all(not c for c in count)',
- }
- def time_test(loops, reps):
- ''' Print timing stats for all the commands '''
- timings = []
- for name, cmd in commands.items():
- setup = 'from __main__ import count'
- t = Timer(cmd, setup)
- result = t.repeat(reps, loops)
- result.sort()
- timings.append((result, name))
- timings.sort()
- for result, name in timings:
- print('{:10} {}'.format(name, result))
- #Find the ratio of slowest / fastest
- tlo, thi = [timings[i][0][0] for i in (0, -1)]
- print('ratio: {:f}'.format(thi / tlo))
- def disassemble():
- ''' Show the bytecode of all the commands '''
- for name, cmd in commands.items():
- print(name)
- dis.dis(cmd)
- print()
- def verify():
- ''' Verify that all commands give the same result '''
- results = [eval(cmd) for cmd in commands.values()]
- #print(results)
- r0 = results[0]
- print(all(r == r0 for r in results[1:]))
- #disassemble()
- # Do the tests.
- reps = 5
- loops = 2000
- #The first test is with no element of `count` set.
- index = None
- for _ in range(10):
- print('\nindex = {}, loops = {}'.format(index, loops))
- verify()
- time_test(loops, reps)
- if index is None:
- index = len(count) - 1
- else:
- index = (index - 1) // 2
- if index > 7:
- loops *= 2
- count[index] = 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement