While writing a script I discovered the numpy.random.choice function. I implemented it because it was was much cleaner than the equivalent if statement. However, after running the script I realized it is significantly slower than the if statement.
The following is a MWE. The first method takes 0.0 s, while the second takes 7.2 s. If you scale up the i loop, you will see how fast random.choice slows down.
Can anyone comment on why random.choice is so much slower?
import numpy as np
import numpy.random as rand
import time as tm
#-------------------------------------------------------------------------------
tStart = tm.time()
for i in xrange(100):
for j in xrange(1000):
tmp = rand.rand()
if tmp < 0.25:
var = 1
elif tmp < 0.5:
var = -1
print('Time: %.1f s' %(tm.time() - tStart))
#-------------------------------------------------------------------------------
tStart = tm.time()
for i in xrange(100):
for j in xrange(1000):
var = rand.choice([-1, 0, 1], p = [0.25, 0.5, 0.25])
print('Time: %.1f s' %(tm.time() - tStart))