什么方法可以使python计数最快?



我正在上一节关于摩尔的化学课以及它有多大。我看到这样的文字:

一台每秒可以计算1000万个原子的计算机将需要20亿年才能数出1摩尔的物质

我觉得向全班演示一下会很酷。所以我有了这个脚本:

import time
t_end = time.time() + 1
i=0
while time.time() < t_end:
    i += 1
print(i)

输出结果:6225324。这是正确的数量级,但肯定低于语句。更有效的写法是什么?

由于time.time()轮询,您的代码中有太多的开销。这是一个系统调用,它不是免费的,所以它使你的计数器相形见绌,使你的测量产生偏差。

在python中我能想到的最好的方法是:

import time
start_time = time.time()
for i in range(1,10000000):  # use xrange if you run python 2 or you'll have problems!!
    pass
print("counted 10 million in {} seconds".format(time.time()-start_time))

在我的电脑上,它花了0.5秒。

当然,python被解释,你会有更好的结果运行它与pypy,或更好:与编译语言,如C(或甚至Java有JIT)。

如果你只是想证明阿伏伽德罗数是一个真的大的数,你可以这样做:

import time 
avo=602214085700000000000000
sec_per_year=60*60*24*365.25
t0=time.time()
for i in range(avo):    
    if i and i%10000000==0:
        t=time.time()-t0
        avg_per_sec=i/t
        per_year=avg_per_sec*sec_per_year
        print("{:15,} in {:,.2f} sec -- only {:,} more to go! (and {:,.2f} years)".format(i, t, avo-i,avo/per_year))

打印:

 10,000,000 in 2.17 sec -- only 602,214,085,699,999,990,000,000 more to go! (and 4,140,556,225.48 years)
 20,000,000 in 4.63 sec -- only 602,214,085,699,999,980,000,000 more to go! (and 4,422,153,353.15 years)
 30,000,000 in 7.12 sec -- only 602,214,085,699,999,970,000,000 more to go! (and 4,530,778,737.84 years)
 40,000,000 in 9.58 sec -- only 602,214,085,699,999,960,000,000 more to go! (and 4,571,379,181.80 years)
 50,000,000 in 12.07 sec -- only 602,214,085,699,999,950,000,000 more to go! (and 4,605,790,562.41 years)
 ...

对于PyPy或Python2,您需要使用while循环,因为xrange溢出了阿伏伽德罗数:

from __future__ import print_function
import time 
avo=602214085700000000000000
sec_per_year=60*60*24*365.25
t0=time.time()
i=0
while i<avo:
    i+=1
    if i and i%100000000==0:
        t=time.time()-t0
        avg_per_sec=i/t
        per_year=avg_per_sec*sec_per_year
        print("{:15,} in {:,.2f} sec -- only {:,} more to go! (and {:,.2f} years)".format(i, t, avo-i,avo/per_year))
在PyPy上,你几乎可以看到结局!

打印:

100,000,000 in 0.93 sec -- only 602,214,085,699,999,900,000,000 more to go! (and 176,883,113.10 years)
200,000,000 in 1.85 sec -- only 602,214,085,699,999,800,000,000 more to go! (and 176,082,858.48 years)
300,000,000 in 2.76 sec -- only 602,214,085,699,999,700,000,000 more to go! (and 175,720,835.29 years)
400,000,000 in 3.68 sec -- only 602,214,085,699,999,600,000,000 more to go! (and 175,355,661.40 years)
500,000,000 in 4.59 sec -- only 602,214,085,699,999,500,000,000 more to go! (and 175,114,044.92 years)
600,000,000 in 5.49 sec -- only 602,214,085,699,999,400,000,000 more to go! (and 174,641,142.93 years)
700,000,000 in 6.44 sec -- only 602,214,085,699,999,300,000,000 more to go! (and 175,612,486.37 years)

相关内容

最新更新