Skip to main content
 首页 » 编程设计

python之在 python 中获取 1 到 100 万之间的随机数的最快方法

2025年05月04日24youxin

实现此目标的绝对最快方法是什么?我每天将执行此操作超过 100 万次,因此我希望效率最高。

使用 numpy(20 次运行后的平均值为 0.0001679009692429128)

t0 = time.clock() 
print(np.random.randint(1,1000000)) 
t1 = time.clock() 
print (t1-t0) 

随机(平均:0.0000920492372555262)

t2 = time.clock() 
print(random.choice(range(1,1000000))) 
t3 = time.clock() 
print (t3-t2) 

令我惊讶的是,random 始终比 numpy 快。有没有更快的方法?

请您参考如下方法:

numpy 在生成大量随机数样本(数组)时效率更高。例如,

In [10]: %timeit np.random.randint(1,1000000, 1000000) 
5.14 ms ± 64.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 
 
In [11]: %timeit [random.choice(range(1,1000000)) for _ in range(1000000)] 
1.01 s ± 14.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 

此外,参见 How can I time a code segment for testing performance with Pythons timeit?关于如何执行时序测试。当您使用 time.clock() 时,您至少应该尝试多次重复该操作,然后计算平均时间。更建议使用 timeit 进行计时测试。此外,正如其他人在评论中提到的那样,print() 生成随机数所花费的时间要长得多,因此您的计时测试主要是衡量 print() 的工作速度。相反,您应该这样做:

In [12]: repeat = 1000000 
    ...: t0 = time.clock() 
    ...: for _ in range(repeat): 
    ...:     np.random.randint(1, 1000000) 
    ...: t1 = time.clock() 
    ...: print((t1 - t0) / repeat) 
1.3564629999999908e-06 
 
In [13]: repeat = 1000000 
    ...: t2 = time.clock() 
    ...: for _ in range(repeat): 
    ...:     random.choice(range(1, 1000000)) 
    ...: t3 = time.clock() 
    ...: print((t3 - t2) / repeat) 
1.0206699999999956e-06 

因此,对于单个数字,numpy 平均比内置随机数生成器慢 35%。然而,之前的测试表明,在生成大样本时,numpy 的速度要快得多。