How to measure elapsed time in Python?

In Python, multiple modules facilitate the measurement of program execution time. The determination of execution time hinges on factors such as the Operating System, Python version, and the specific interpretation of "time" being considered.

Using time module in Python

The time() function yields the count of seconds elapsed since the epoch. Specifically, the time.time() function from the time module provides this functionality, returning the time in seconds since the epoch. It's important to note that the treatment of leap seconds can vary based on the platform. Utilizing time.time() allows for the measurement of elapsed wall-clock time between two distinct points in a program's execution.

import time startTime = time.time() print("Program running....") endTime = time.time() print(endTime - startTime)
Output: Program running.... 4.0531158447265625e-06

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

The datetime.timedelta class in Python serves as a means to represent durations, expressing the disparity between two instances of date, time, or datetime down to microsecond precision. This functionality extends to the addition of days, minutes, seconds, hours, weeks, and other units to instances of datetime.date or datetime.datetime. By using datetime.timedelta, you can ascertain execution time in seconds, as illustrated in the provided program. This class proves indispensable for various time-related calculations and measurements.

import time from datetime import timedelta startTime = time.time() print("Program running....") endTime = time.time() print(endTime - startTime) print("Execution time in seconds :") print(timedelta(seconds=endTime-startTime))
Output: Program running.... 3.5762786865234375e-06 Execution time in seconds : 0:00:00.000004
  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

The Python timeit module furnishes a convenient mechanism to determine the execution time of concise sections of Python code. It adeptly circumvents numerous pitfalls often associated with measuring execution durations. By repeatedly executing your code snippet millions of times (defaulting to 1,000,000), the timeit module yields a statistically significant measurement of code execution time, enabling accurate performance assessment. This module proves invaluable for precise benchmarking and profiling of code segments.

import timeit executionTime = timeit.timeit(lambda: "print('Hello World!')") print(executionTime) //output:0.26035445800516754

timeit.default_timer

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:

from timeit import default_timer as timer startTime = timer() print("Program running....") endTime = timer() print(endTime - startTime)
Output: Program running.... 3.978959284722805e-06

The default_timer() function for measurement may encounter interference from concurrent Python programs running on the same system. Hence, when utmost timing accuracy is essential, a recommended practice is to conduct multiple timing iterations and select the optimal result. For Unix systems, time.clock() can be employed to gauge CPU time consumption, providing a distinct perspective on program execution duration. This approach ensures that timing assessments are refined and tailored to specific accuracy requirements, enhancing the reliability of execution time measurements.

Using Datetime Module

The datetime module offers the capability to calculate the time elapsed within a code block, although it's important to note that this approach might not deliver high precision. The resulting output is presented in the format of HH:MM:SS, which represents hours, minutes, and seconds. While this method can provide a general sense of time elapsed, it's advisable to consider alternative methods for more accurate and granular timing measurements when necessary.

from datetime import datetime startTime = datetime.now() print("Program running....") endTime = datetime.now() print(endTime - startTime)
Output: Program running.... 0:00:00.000006

Elapsed Time as Days, Hours, Minutes and Seconds

from datetime import datetime as dt startTime = dt.fromtimestamp(1588432670) endTime = dt.now() elapsed=endTime-startTime print("Elapsed Time : %02d:%02d:%02d:%02d" % (elapsed.days, elapsed.seconds // 3600, elapsed.seconds // 60 % 60, elapsed.seconds % 60))
Output: Elapsed Time : 817:15:37:50

Conclusion

Various methods are available to measure elapsed time during program execution. The time module's time() function can capture seconds since the epoch, while the datetime module's timedelta class offers precise duration calculations. The timeit module facilitates accurate benchmarking, and default_timer() can provide timing insights, although for high precision, repetition and selection of the best result are recommended.