Measure time with Python when device's epoch time is unreliable

317 views Asked by At

I need to count the number of seconds that have passed between the execution of some code on a Raspberry Pi. Normally I'd do it as follows in Python:

start = time.time()
execute_my_function()
end = time.time()
elapsed = end - start

However, the Raspberry Pi doesn't include an RTC and instead relies on NTP. This means that for the first little while after booting, the system time is January 1, 1970, and so the difference between "end" and "start" often becomes about 47 years.

How do I measure the elapsed time in seconds if the system time is unreliable (from what I can gather, the "timeit" module relies on "time" and thus won't work either)? It doesn't have to be completely accurate--a second or two too much or too little is fine.

Edit: I've made a sort of hack where I read /proc/uptime which I believe is independent of the system time, but I kind of feel dirty this way. I'm hoping there is a somewhat less OS dependent solution.

1

There are 1 answers

0
PaulMcG On

You could have your program wait until start_time has a meaningful value:

while time.time() < 1e6:
    time.sleep(10)