Just want to generate random number in a range (no matter float or integer) by using Python. Since I only need to get a random number in my code once a time, the speed for calling the generating-function is critical.
So let’s do the experiment:
import random
import time
import numpy as np
begin = time.time()
for i in range(10000):
random.uniform(1, 100)
print('time:', time.time() - begin)
begin = time.time()
for i in range(10000):
random.randrange(1, 100)
print('time:', time.time() - begin)
begin = time.time()
for i in range(10000):
np.random.uniform(1, 100)
print('time:', time.time() - begin)
The result is:
time: 0.0025768280029296875 time: 0.00877070426940918 time: 0.022496461868286133
Looks the random.uniform() from standard library of Python3 is the fastest one. But there is still a odd phenomenon: numpy is as fast as we expected.
Actually, the correct way of using numpy.random.uniform() is setting its size argument.
begin = time.time()
for i in range(10000):
np.random.uniform(1, 100)
print('time:', time.time() - begin)
begin = time.time()
np.random.uniform(1, 100, 10000)
print('time:', time.time() - begin)
The result is:
time: 0.022496461868286133 time: 0.00012969970703125
Thus the best way to generating a bunch of random numbers at a time is numpy.random.uniform()