Python计算的运行时间结果是n

2024-04-27 03:46:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用时间来记录这个函数的运行时间,但是我觉得结果不正确,有时只花费0,结果不稳定。The first two result is for N=10000, the third one is N=30000

import time
def sumOfN(n):
    start=time.time()
    theSum=0
    for i in range(1,n+1):
        theSum=theSum+i
    end=time.time()
    return theSum,end-start
for i in range(5):
    print("Sum is %d required %10.7f seconds"%sumOfN(300000))

Tags: the函数infortimeis记录时间
1条回答
网友
1楼 · 发布于 2024-04-27 03:46:30

根据the Python manual

time.time()

Return the time in seconds since the epoch as a floating point number. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

(强调矿山)

系统的计时器分辨率似乎不足以正确测量函数的运行时间。实际上看起来精度大约是0.016,大约1/60秒,这是典型的Windows系统。你知道吗

您的方法有以下两个问题:

  • time.time()返回当前时间(如一天中的某个时间),可以通过自动调整进程(如NTP)或有人修改(手动或通过代码)来改变当前时间。使用^{}(或Python<;3.3中的time.clock())代替。你知道吗
  • 您正在测量函数的执行情况。由于垃圾收集、字节码优化和Python等语言的其他特性的不确定性,这可能会导致非常错误的结果。您应该查看^{}模块。你知道吗

相关问题 更多 >