Reputation: 33
I trying to use time to record running time of this function, but i think the result is not correct, sometimes it will only cost 0s and the result is not stable.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))
Upvotes: 0
Views: 281
Reputation: 14185
According to 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.
(emphasis mine)
It seems the timer resolution of your system is not enough to correctly measure the elapsed time of the function. It actually looks like the precision is about 0.016, about 1/60 of a second, which is typical of Windows systems.
your approach has the following two problems:
time.time()
returns the current time (as in time of day), which can vary by auto-adjusting processes such as NTP or if someone modifies it (either by hand or via code). Use time.perf_counter()
(or time.clock()
in Python <3.3) instead.timeit
module instead.Upvotes: 2