DEV Community

Cover image for How to not leap in time using Python
luminousmen
luminousmen

Posted on • Edited on

How to not leap in time using Python

If you want to display the time to a user of your application, you query the time of day. However, if your application needs to measure elapsed time, you need a timer that will give the right answer even if the user changes the time on the system clock.

The system clock which tells the time of day is referred to as a real-time clock or a wall clock. The time on such a clock will jump when changed. Relying on the wall-clock to find out how much time has passed since a previous event is a bug waiting to happen.

For example, suppose your application carries out an operation in response to some event, but it only executes that operation once an hour, it does nothing in between. Maybe the operation is some kind of clean-up task. Suppose the user made a typo and set the wrong month on the system clock before your application started; he might then fix that later when your application already working. Suppose the date is now a month earlier than when your application started, it will be a month until your application thinks that it should carry out its clean-up operations again!

To safely measure elapsed time in an application, you need a clock that measures time continuously, without any jumps when a user sets the system time. This kind of clock is called a monotonic clock. Python 3.3 introduced the time.monotonic() function to provide a basic monotonic clock. Before python 3.3 there’s a PyPI module called monotonic that provides similar functionality.

import time

start = time.monotonic()
time.sleep(0.2)
end = time.monotonic()

print("start: {:>9.2f}".format(start))
print("end: {:>9.2f}".format(end))
print("span: {:>9.2f}".format(end - start))
Enter fullscreen mode Exit fullscreen mode
start:   4601.77
end:   4601.97
span:      0.20
Enter fullscreen mode Exit fullscreen mode

To measure performance, it is important to have monotonic timers with high accuracy. Such a timer Python provides in time.perf_counter():

import time

start = time.perf_counter()
i = 0
while i < 100000:
    i = i + 1

elapsed_time = time.perf_counter() - start
print("Elapsed time: {}".format(elapsed_time))
Enter fullscreen mode Exit fullscreen mode
Elapsed time: 0.012327131999882113
Enter fullscreen mode Exit fullscreen mode

From Python 3.8 time.clock() function will be deleted and time.perf_counter() will be used.


Thank you for reading!

Any questions? Leave your comment below to start fantastic discussions!

Check out my blog or come to say hi 👋 on Twitter or subscribe to my telegram channel.
Plan your best!

Top comments (0)