如果你只是想證明,阿伏加德羅常數的是真的大的數字,你可以做這樣的事情:
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)
我不明白的問題。你是否要求一種更有效的方法來在Python中進行增量?或者你問爲什麼你的代碼只執行這麼多迭代/增量? – UnholySheep
有沒有一種更有效的方式來做增量可能是一個更好的措辭。 –
然後答案是「否」。如果你需要更快的性能,你必須切換到不同的編程語言(例如:C甚至彙編語言),儘管我不確定你是否真的會看到這麼多差異。 – UnholySheep