How to Not Leap in Time Using Python

DZone 's Guide to

How to Not Leap in Time Using Python

See how time.perf_counter() works in Python.

· Web Dev Zone ·
Free Resource

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 and 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; they 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!

You may also like: My Journey With Python (Part I).

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()
end = time.monotonic()

print("start: {:>9.2f}".format(start))
print("end: {:>9.2f}".format(end))
print("span: {:>9.2f}".format(end - start))

start:   4601.77
end:   4601.97
span:      0.20

To measure performance, it is important to have monotonic timers with high accuracy. Python provides a timer with 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))

Elapsed time: 0.012327131999882113

From Python 3.8, the 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!

Further Reading

python ,time

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}