The result of running time calculated by Python is not correct
Question: 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](http://i.stack.imgur.com/kyYpb.png)

    
    
    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))
    


Answer: According to [the Python
manual](https://docs.python.org/3/library/time.html#time.time):

> ## `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()`](https://docs.python.org/3/library/time.html#time.perf_counter) (or `time.clock()` in Python <3.3) instead_.
  * You are measuring _one_ execution of the function. This can give you very wrong results due to the non-deterministic nature of garbage collection, bytecode optimization, and other quirks of languages like Python. You should look into the [`timeit`](https://docs.python.org/3/library/timeit.html) module instead.

