【问题标题】:Timing a Python program using time.clock() vs. time.time() [duplicate]使用 time.clock() 与 time.time() 为 Python 程序计时 [重复]
【发布时间】: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秒


我的问题是

  1. 上面计算的时间是否正确?
  2. time.time() 与 time.clock() 之间有什么区别。如果我使用 time.time() 我得到 0.0 作为时间。

【问题讨论】:

  • 从 Code Review 迁移而来,因为问题不是要求开放式改进建议,而是要求对特定编程问题进行解释。

标签: python python-3.x benchmarking


【解决方案1】:

在 Python time module 中,time.clock() 测量自第一次调用函数以来的时间(以秒为单位),time.time() 测量自 1970 年 1 月 1 日以来的时间,以秒为单位。

time.clock() 通常更精确,所以我建议使用它。这就是为什么在第一个示例中结果很小,在第二个示例中舍入为零的原因。

【讨论】:

    猜你喜欢
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多