pythontimeclockntpraspberry-pi-zero

Python: Elapsed time without using system clock


I need to measure the elapsed time of a program that waits for an input.

However, my system clock will not be stable when measuring this - I am using a Pi 0 that does not have an RTC, so on bootup the clock is off. However, the clock will sync to NTP when it connects to the internet. Waiting for internet before starting the program is not an option.


I am currently using `time.time()` at the beginning and end, and subtracting the values.
start = time.time()
# wait for input and complete tasks
end = time.time()
elapsed=end-start

This fails because when the NTP syncs, it can change the value of time.time() by over 20 minutes. This drastically changes my elapsed time.

I would like a similar system of timing, however even when the system clock changes, it stays constant.


Solution

  • I ended up using time.monotonic()

    the reference point of the returned value of the monotonic clock is undefined, only the difference between the results of consecutive calls is valid.

    https://www.geeksforgeeks.org/python-time-monotonic-method/

    It can be used exactly like time.time() in the example, but it can only be used to calculate differences in time, as the number itself is initially randomized.