【发布时间】:2017-01-11 14:05:16
【问题描述】:
我是 Python 编程新手。我今天早上开始研究 Project Euler,我想知道执行我的解决方案需要多长时间。我已经在网上搜索了解决我的问题的方法
import time
class Solution(object):
def fibonacci(self,limit):
sum = 0
current = 1
next = 2
while(current <= limit):
if current % 2==0:
sum += current
current, next = next, current + next
return str(sum)
if __name__ == "__main__":
start = time.clock()
solution = Solution().fibonacci(4000000)
elapsed = time.clock()-start
print("Solution: %s"%(solution))
print("Time: %s seconds"%(elapsed))
输出:
解决方案:4613732
时间:2.006085436846098e-05秒
import time
class Solution(object):
def fibonacci(self,limit):
sum = 0
current = 1
next = 2
while(current <= limit):
if current % 2==0:
sum += current
current, next = next, current + next
return str(sum)
if __name__ == "__main__":
start = time.time()
solution = Solution().fibonacci(4000000)
elapsed = time.time()-start
print("Solution: %s"%(solution))
print("Time: %s seconds"%(elapsed))
输出:
解决方案:4613732
时间:0.0秒
我的问题是
- 上面计算的时间是否正确?
- time.time() 与 time.clock() 之间有什么区别。如果我使用 time.time() 我得到 0.0 作为时间。
【问题讨论】:
-
从 Code Review 迁移而来,因为问题不是要求开放式改进建议,而是要求对特定编程问题进行解释。
标签: python python-3.x benchmarking