在python中生成1,000,000+随机数的最快方法

在python中生成1,000,000+随机数的最快方法,第1张

在python中生成1,000,000+随机数的最快方法

您可以通过执行您最初描述的 *** 作(生成一堆随机数并相应地相乘和相除)来加快上述mtrw的速度

另外,您可能已经知道这一点,但是在使用大型numpy数组时,请确保就地进行 *** 作(* =,/ =,+
=等)。对于大型数组,这在内存使用方面产生了巨大的差异,并且还将显着提高速度。

In [53]: def rand_row_doubles(row_limits, num):   ....:     ncols = len(row_limits)   ....:     x = np.random.random((num, ncols))   ....:     x *= row_limits          ....:     return x       ....:      In [59]: %timeit rand_row_doubles(np.arange(7) + 1, 1000000)10 loops, best of 3: 187 ms per loop

相比于:

In [66]: %timeit ManyRandDoubles(np.arange(7) + 1, 1000000)1 loops, best of 3: 222 ms per loop

差别不大,但是如果您 真的 担心速度,那就好了。

只是为了证明它是正确的:

In [68]: x.max(0)Out[68]:array([ 0.99999991,  1.99999971,  2.99999737,  3.99999569,  4.99999836,        5.99999114,  6.99999738])In [69]: x.min(0)Out[69]:array([  4.02099599e-07,   4.41729377e-07,   4.33480302e-08,         7.43497138e-06,   1.28446819e-05,   4.27614385e-07,         1.34106753e-05])

同样,对于您的“行加总”部分,…

In [70]: def rand_rows_sum_to_one(nrows, ncols):   ....:     x = np.random.random((ncols, nrows))   ....:     y = x.sum(axis=0)   ....:     x /= y   ....:     return x.T   ....:In [71]: %timeit rand_rows_sum_to_one(1000000, 13)1 loops, best of 3: 455 ms per loopIn [72]: x = rand_rows_sum_to_one(1000000, 13)In [73]: x.sum(axis=1)Out[73]: array([ 1.,  1.,  1., ...,  1.,  1.,  1.])

老实说,即使您重新实现C语言中的功能,但我不确定您在这方面是否能胜过numpy …不过,我可能错了!



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5639987.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存