Trying to time different random functions to see fastest way to choose random item from list. %timeit
wants to give me "best of 3" fastest times, but because the runs are random, there's high variance in access times (grab from back of list, will be slow; grab from front, will be fast).
How do I get average across all loops, not best of?
a = [0,6,3,1,3,9,4,3,2,6]
%timeit random.choice(a)
%timeit a[random.randint(0,len(a)-1)]
%timeit a[np.random.randint(0,len(a)-1)]
%timeit np.random.choice(a,1)[0]
Currently output (acknowledging variance in timing):
%timeit random.choice(a)
The slowest run took 9.87 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1.23 µs per loop
Update: a kludge approach:
%time for i in range(100000): random.choice(a)
%time for i in range(100000): a[random.randint(0,len(a)-1)]
%time for i in range(100000): a[np.random.randint(0,len(a)-1)]
%time for i in range(100000): np.random.choice(a,1)[0]
np.random.choice
castsa
to an array, which can be quite expensive. I see about a factor of 6 difference for alen(10)
list vs array. – Joselyna
list as an example. But thanks for thought! – Fingerboard