Created
June 9, 2017 12:59
-
-
Save PM2Ring/b916ff5246e5265e91821c0bbd18a96d to your computer and use it in GitHub Desktop.
Compare speed of random.shuffle with sort using a random key
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 | |
''' Compare the speeds of random.shuffle | |
with sorted using a random key function | |
Written by PM 2Ring 2017.06.09 | |
Python 2 / 3 compatible | |
''' | |
from __future__ import print_function, division | |
from timeit import Timer | |
from random import random, seed, shuffle | |
# The functions to test | |
def randsort(seq, key=lambda x: random()): | |
seq.sort(key=key) | |
def randsorted(seq, key=lambda x: random()): | |
return sorted(seq, key=key) | |
funcs = ( | |
shuffle, | |
randsort, | |
#randsorted, | |
) | |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
def time_test(loops, reps): | |
''' Print timing stats for all the functions ''' | |
timings = [] | |
for func in funcs: | |
fname = func.__name__ | |
setup = 'from __main__ import seq, ' + fname | |
cmd = fname + '(seq)' | |
t = Timer(cmd, setup) | |
result = t.repeat(reps, loops) | |
result.sort() | |
timings.append((result, fname)) | |
timings.sort() | |
for result, fname in timings: | |
print('{0:12} {1}'.format(fname, result)) | |
seed(163) | |
# Do the timing tests | |
reps = 3 | |
loops = 1 << 15 | |
for i in range(1, 12): | |
n = 1 << i | |
seq = list(range(n)) | |
print('\n{0}: Size={1}, Loops={2}'.format(i, n, loops)) | |
time_test(loops, reps) | |
loops >>= 1 | |
#loops = 1000 | |
#for n in range(100, 200, 10): | |
#seq = list(range(n)) | |
#print('\nSize={0}, Loops={1}'.format(n, loops)) | |
#time_test(loops, reps) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment