How to measure elapsed time in Python?

In Python, there are several modules that help you to find the execution time of a program. Measuring the execution time of a program depends on your Operating System, Python version, and what you mean by "time".

Using time module in Python

The time() function returns the number of seconds passed since epoch. The time.time() function of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent. You can use time.time() to measure the elapsed wall-clock time between two points:

In the above code, the difference between the endTime and startTime, which gives the execution time. It is important to note that, the execution time depends on the Operating System.

Measuring Python execution time in seconds

Python Measure the Execution Time of a Program

Python datetime.timedelta is a duration expressing the difference between two date, time, or datetime instances to microsecond resolution. With timedelta you can add days, minutes, seconds, hours, weeks and more to a, or a datetime.datetime object. In the following program, you can measure execution time in seconds using timedelta.

  1. On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of "processor time", depends on that of the 'C' function of the same name.
  2. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Using timeit module in Python

Python timeit module provides a simple way to find the execution time of small bits of Python code. It avoids a number of common traps for measuring execution times. This module runs your snippet of code millions of times (default value is 1000000) so that you get the statistically most relevant measurement of code execution time.


Also you can use timeit.default_timer instead of timeit.timeit. The default_timer provides the best clock available on your platform and version of Python automatically:

The default_timer() measurement can be affected by other Python programs running on the same machine, so the best thing to do when accurate timing is necessary is to repeat the timing a few times and use the best time. On Unix, you can use time.clock() to measure CPU time.

Using Datetime Module

Datetime module can also be used to find the time elapsed or spent in a code block provided you are not looking for high precision. The program return in HH:MM:SS format.

Elapsed Time as Days, Hours, Minutes and Seconds
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About