
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to measure time with high-precision in Python?
Python provides various modules, such as time, datetime, and timeit, to measure time with high accuracy. These modules offer high-resolution clocks to measure time intervals.
The following are several methods used to measure time with high precision in Python.
Using time.time() Method for Simple Timing
The time.time() method returns the current time in seconds since the epoch as a floating-point number. The epoch is system-dependent, but on Unix-like systems, it is typically January 1, 1970, 00:00:00 (UTC).
Example
The following program measures the time taken to execute a loop that multiplies numbers. It uses time.time() to capture the start and end times, then prints the total elapsed time in seconds:
import time start = time.time() for i in range(1000000): _ = i * 2 end = time.time() print("Time taken:", end - start, "seconds")
Following is the output of the above code:
Time taken: 0.09123420715332031 seconds
Using time.perf_counter() Function
The time.perf_counter() function is used to measure short durations. It provides the highest available resolution timer and also includes time elapsed even when the local system is in sleep.
Example
The following program measures the execution time using time.perf_counter() function. It records the start and end times of a loop that performs a simple multiplication operation (1 million times), then calculates and prints the elapsed time with high precision:
import time start = time.perf_counter() for i in range(1000000): _ = i * 2 end = time.perf_counter() print("High precision time taken:", end - start, "seconds")
Following is the output of the above code:
High precision time taken: 0.087654321 seconds
Using timeit.default_timer()
The default_timer() function is defined in Python's timeit module. This function is used for precise time measurements. It selects the most accurate timer available on your system (e.g., time.perf_counter() or time.time()) based on the platform.
Example
In the following program, we are measuring the precise execution time of a loop by using timeit.default_timer() function. The 'start' records the beginning time, 'end' captures the end, and their difference gives the high-precision duration in seconds:
from timeit import default_timer as timer start = timer() for i in range(1000000): _ = i * 2 end = timer() print("Time measured using timeit:", end - start, "seconds")
Following is the output of the above code:
Time measured using timeit: 0.089123 seconds