Created
December 9, 2017 11:06
-
-
Save PM2Ring/7a9de9d211e43b3a8f7cf8362913bc95 to your computer and use it in GitHub Desktop.
Test speeds of various ways of creating a list of random bits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
''' Test speeds of various ways of creating a list of random bits | |
Typical results on a 32bit 2GHz machine running Python 3.6.0 on Linux | |
null : [0.04344886299986683, 0.04375551599878236, 0.04837666000094032] | |
zipgen : [0.28622414100027527, 0.28712629300025583, 0.2921328890006407] | |
nextgen : [0.363577712998449, 0.3746541500004241, 0.3797654469999543] | |
randrange : [1.342143091998878, 1.3589175790002628, 1.3717609110008198] | |
randint : [1.792100284999833, 1.8232857450002484, 1.8753145200007566] | |
Written by PM 2Ring 2017.12.09 | |
''' | |
from timeit import Timer | |
from random import seed, getrandbits, randrange, randint | |
#seed(42) | |
def randbit(blocksize=32): | |
while True: | |
n = getrandbits(blocksize) | |
for _ in range(blocksize): | |
yield n & 1 | |
n >>= 1 | |
num = 1<<10 | |
randbitgen = randbit() | |
cmds = ( | |
('null', '[0 for _ in range(num)]'), | |
('zipgen', '[u for _,u in zip(range(num), randbitgen)]'), | |
('nextgen', '[next(randbitgen) for _ in range(num)]'), | |
('randrange', '[randrange(2) for _ in range(num)]'), | |
('randint', '[randint(0, 1) for _ in range(num)]'), | |
) | |
def time_test(loops): | |
timings = [] | |
setup = 'from __main__ import randbitgen, num, randrange, randint' | |
for name, cmd in cmds: | |
t = Timer(cmd, setup=setup) | |
result = sorted(t.repeat(3, loops)) | |
timings.append((result, name)) | |
timings.sort() | |
for result, name in timings: | |
print('{:10} : {}'.format(name, result)) | |
loops = 200 | |
time_test(loops) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment