請教 Python 的寫法?

69 views
Skip to first unread message

高顯忠

unread,
Nov 19, 2014, 7:11:15 AM11/19/14
to tos...@googlegroups.com
目前已經會寫Python 的朋友,請幫忙測試一下,
1 + 2 + 3 + . . . + 2000000000= ???
需要多少時間?
如果需要太久的時間,算不出來,
可以把 2000000000 --> 改成 10, 100, 1000, 10000, 100000, . . .
先 謝謝啦!

王瑋強

unread,
Jul 28, 2015, 9:29:07 AM7/28/15
to TOSSUG, sjga...@gmail.com
如果是因為花費太多時間,可以利用 1+ 2+ 3 + ... +n = n(n+1) /2 的公式計算比較快囉。瞬間計算完畢。
單純測試效能使用for迴圈的話,就沒有測試囉。


高顯忠於 2014年11月19日星期三 UTC+8下午8時11分15秒寫道:

FourDollars

unread,
Jul 28, 2015, 9:53:25 PM7/28/15
to TOSSUG, redhe...@gmail.com, sjga...@gmail.com, redhe...@gmail.com
我在最低階的 ThinkPad X200 上面的執行結果

$ time python -c "print(str(reduce(lambda x, y: x + y, [i for i in range(1, 10000000+1)])))"
50000005000000

real 0m3.108s
user 0m2.654s
sys 0m0.379s

$ time python3 -c "from functools import reduce; print(reduce(lambda x, y: x + y, [i for i in range(1, 10000000+1)]))"
50000005000000

real 0m2.799s
user 0m2.408s
sys 0m0.375s

參考看看

王瑋強於 2015年7月28日星期二 UTC+8下午9時29分07秒寫道:
Reply all
Reply to author
Forward
0 new messages