简体   繁体   中英

Why does measuring execution time with time module randomly output 0 seconds?

import time

start_time = time.time()
print('Running time :')
print(time.time()-start_time)

it's gotta be more than 0, so 0 should not come out. This code sometimes outputs correctly like below.

Running time :
0.0009982585906982422

But sometimes it outputs 0 seconds.

Running time :
0.0

Why is this happening? I first suspected it being rounded, but judging from the correct result one, it seems even if they did, it wouldn't put out 0 as it has lots of digits below the point.

The builtin time module is not meant to be used to time programs, especially such short ones. From the official doc :

The precision of the various real-time functions may be less than suggested by the units in which their value or argument is expressed. Eg on most Unix systems, the clock “ticks” only 50 or 100 times a second.

To precisely time your program, use the timeit module which is meant for it, and takes care of some details like disabling garbage collection etc... to get a more precise timing.

>>> import timeit
>>> timeit.timeit('print("hello")', number=1000)
0.14811120001832023

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM