我对一些随机整数生成代码的速度产生了好奇。 我编写了以下代码来进行测试:
from random import random
from random import choice
from random import randint
from math import floor
import time
def main():
times = 1000000
startTime = time.time()
for i in range(times):
randint(0,9)
print(time.time()-startTime)
startTime = time.time()
for i in range(times):
choice([0,1,2,3,4,5,6,7,8,9])
print(time.time()-startTime)
startTime = time.time()
for i in range(times):
floor(10*random())##generates random integers in the same range as randint(0,9)
print(time.time()-startTime)
main()
该代码的一次试验结果为:
即使执行了乘法和math.floor,最终生成整数的最快方式仍然是随机方式。改变生成数字范围的大小并没有改变任何事情。0.9340872764587402
0.6552846431732178
0.23188304901123047
那么,为什么随机方式比randint更快呢?除了易于使用、可读性好以及不容易出错等原因外,有没有人喜欢randint而不是random(例如,randint产生更多的伪随机整数)?如果floor(x * random())感觉不够可读,但你想要更快的代码,你应该选择专门的程序吗?
def myrandint(low,high): ###still about 1.6 longer than the above, but almost 2.5 times faster than random.randint
return floor((high-low+1)*random())+low ##returns a random integer between low and high, inclusive. Results may not be what you expect if int(low) != low, etc. But the numpty who writes 'randint(1.9,3.2)' gets what they deserve.
randint
函数使用了randrange
,而它在 Python 中的实现有很多开销:https://github.com/python/cpython/blob/master/Lib/random.py#L211 基本上,在每次调用函数时,它都会进行大量错误检查。 如果你不需要这些检查,当然可以使用一个更简单的实现。 - ayhanfloor(n*random())
计算[0, n)
中的整数存在偏差。对于n=10
,这种偏差在统计上是无法检测到的,但对于较大的n
可能会有问题。请参见 https://bugs.python.org/issue9025 以了解更多讨论。 - Mark Dickinson