Image for post
Image for post

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.

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

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!

Written by

helping robots conquer the earth and trying not to increase entropy using Python, Big Data, Machine Learning. Check out my blog —

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store