为什么(在Python中是random.randint比random.random慢得多?

问题描述 投票:0回答:1

我对某些随机整数生成代码的相对速度感到好奇。我写了以下内容进行检查:

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()

此代码的一次试用结果为

0.9340872764587402

0.6552846431732178

0.23188304901123047

即使执行乘法和math.floor之后,生成整数的最终方法仍然是最快的。处理产生数字的范围大小没有任何变化。

所以,为什么随机方式比randint更快?并且有什么理由(除了易用性,可读性和不引人注意的错误)之外,人们更喜欢randint而不是随机数(例如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.

python random
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.