I am trying to use time.perf_counter_ns to time how long something takes in my code. It all works as expected if the code looks like this:
import time
total = 0
num_samples = 1000
for i in range(num_samples):
s = time.perf_counter_ns()
e = time.perf_counter_ns()
total += e - s
print(total/num_samples)
$ python3 test.py
91.507
However, when I add a time.sleep(1) in an unrelated spot in the code, the time I am measuring is higher:
import time
total = 0
num_samples = 1000
time.sleep(1) # <<< I didnt think this should matter!!
for i in range(num_samples):
s = time.perf_counter_ns()
e = time.perf_counter_ns()
total += e - s
print(total/num_samples)
$ python3 test.py
417.304
So, why does adding a time.sleep(1) in a seemingly unrelated spot in the code makes a difference?
Using:
Python 3.8.10 (default, Sep 28 2021, 16:10:42)
[GCC 9.3.0] on linux