我正在做一个关于 the mole 的化学课,以及它的数量有多大。我遇到的文字说:
每秒可以计算10,000,000个原子的计算机 计算1摩尔物质的2,000,000,000年
我认为向班级证明这一点会很酷。所以我有脚本:
import time
t_end = time.time() + 1
i=0
while time.time() < t_end:
i += 1
print(i)
打印结果:6225324
。这是正确的数量级,但绝对低于声明。什么是更有效的方式来写这个?
答案 0 :(得分:3)
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这样的编译语言(甚至是带有JIT的Java)。
答案 1 :(得分:2)
如果您只想证明Avogadro的号码是真正的大号,您可以这样做:
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溢出了avogadros数字:
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)