Skip to content

Instantly share code, notes, and snippets.

@taikedz
Last active March 26, 2021 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taikedz/260c48b671a0e5e1f36bb9985a140b5c to your computer and use it in GitHub Desktop.
Save taikedz/260c48b671a0e5e1f36bb9985a140b5c to your computer and use it in GitHub Desktop.
Get the sample frequency on a loop call to `time.time()`

Time Sampling

I was curious to know what level of precision I could get when using time.sleep(x), like, if it made any sense to try and sleep for say 0.0132 seconds.

It turns out, it does. On a Windows machine with a 1.6GHz processor, I get a sample rate such:

$ python3 time_sampling.py 6
Average step over 1000000 (100.0%) iterations: 2.77e-07
Sample frequency: 3.61 MHz

That is, nearly four million samples.

First argument of the script is a decimal order of magnitude (power of 10, denoting the iterations to perform).

import time
import sys
all_times = []
t0 = time.time()
t1 = t0
iterations_max = 10**int(sys.argv[1])
try:
for iterations in range(1,iterations_max+1):
t1 = time.time()
all_times.append(t1-t0)
t0 = t1
except KeyboardInterrupt:
# In case we passed an insanely high number of iterations
# We want to still get values out for our iterations
pass
avg = sum(all_times)/iterations
scaled_freq = 1/avg
scale = ["", "K", "M", "G", "T"]
scale_idx = 0
kstep = 1000
for magnitude in scale:
if scaled_freq > kstep:
scale_idx += 1
scaled_freq = scaled_freq/kstep
print("Average step over {} ({}%) iterations: {:.2e}".format(iterations, (100.0*iterations/iterations_max), avg))
print("Sample frequency: {:.2f} {}Hz".format(scaled_freq, scale[scale_idx]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment