Skip to content

Instantly share code, notes, and snippets.

@bwesterb
Created April 21, 2013 21:01
Show Gist options
  • Save bwesterb/5431057 to your computer and use it in GitHub Desktop.
Save bwesterb/5431057 to your computer and use it in GitHub Desktop.
Faster random.shuffle for PyCrypto
import math
import random
import timeit
import functools
import Crypto.Random.random
def shuffle(s):
r = Crypto.Random.random.randrange(0, math.factorial(len(s)))
for i in xrange(len(s)-1, 0, -1):
r, j = divmod(r, i+1)
s[i], s[j] = s[j], s[i]
print 'Python random.shuffle'
print timeit.repeat(functools.partial(random.shuffle,
range(100)), number=50, repeat=3)
print
print 'PyCrypto random.shuffle'
print timeit.repeat(functools.partial(Crypto.Random.random.shuffle,
range(100)), number=50, repeat=3)
print
print 'Suggested new PyCrypto random.shuffle'
print timeit.repeat(functools.partial(shuffle,
range(100)), number=50, repeat=3)
@bwesterb
Copy link
Author

Python random.shuffle
[0.002240896224975586, 0.0022079944610595703, 0.0021600723266601562]

PyCrypto random.shuffle
[0.49704694747924805, 0.4917750358581543, 0.49774813652038574]

Suggested new PyCrypto random.shuffle
[0.012892007827758789, 0.013159990310668945, 0.012893199920654297]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment