Skip to main content
 首页 » 编程设计

python之使用 time.clock() 与 time.time() 为 Python 程序计时

2024年10月17日7EasonJim

<分区>

我是 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 作为时间。