When using pythons random.shuffle
function, I noticed it went significantly faster to use sorted(l, key=lambda _: random.random())
than random.shuffle(l)
. As far as I understand, both ways produce completely random lists, so why does shuffle
take so much longer?
Below are the times using timeit
module.
from timeit import timeit
setup = 'import random\nl = list(range(1000))'
# 5.542 seconds
print(timeit('random.shuffle(l)', setup=setup, number=10000))
# 1.878 seconds
print(timeit('sorted(l, key=lambda _: random.random())', setup=setup, number=10000))
Aucun commentaire:
Enregistrer un commentaire