Home > Software design >  perf_counter is returning wrong time
perf_counter is returning wrong time

Time:01-08

I ran this simple code:

import time
print(time.perf_counter())

But for some reason, the output is 9851.549930951. The code takes less than a second to run, and I am not using perf_counter_ns. This is a problem in other programs too. perf_counter outputs 9000 instead of 0.9 for the number of seconds it takes for a thread to finish the execution. The output is always quick and yet the answer is always 9000 like in 9851.549930951.

CodePudding user response:

Did you read the documentation? time.perf_counter()

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid. (emphasis mine)

So you do:

import time

start = time.perf_counter()

# ....

print (time.perf_counter() - start)

To get better performance measurements (avg of multiple runs) you may want to look into timeit instead.

  •  Tags:  
  • Related