Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
time.perf_counter() function in Python
In this tutorial, we are going to learn about the time.perf_counter() method in Python. This function is part of the time module and provides the highest available resolution to measure a short duration.
The method time.perf_counter() returns a float value representing time in seconds. It includes time elapsed during sleep and is system-wide, making it ideal for measuring elapsed time in code execution.
Basic Usage
Let's start with a simple example to see how perf_counter() works ?
import time
# Get current performance counter value
print("Current time:", time.perf_counter())
Current time: 263.3530349
Measuring Execution Time
The most common use case is measuring how long a piece of code takes to execute. Here's how to measure execution time ?
import time
def is_prime(number):
if number < 2:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
# Measure execution time
number = 17377
start_time = time.perf_counter()
result = is_prime(number)
end_time = time.perf_counter()
execution_time = end_time - start_time
print(f"Number {number} is prime: {result}")
print(f"Execution time: {execution_time:.6f} seconds")
Number 17377 is prime: True Execution time: 0.000842 seconds
Comparing Multiple Operations
You can compare the performance of different approaches using perf_counter() ?
import time
# Method 1: Using list comprehension
start_time = time.perf_counter()
squares_list = [i**2 for i in range(10000)]
end_time = time.perf_counter()
time1 = end_time - start_time
# Method 2: Using regular loop
start_time = time.perf_counter()
squares_loop = []
for i in range(10000):
squares_loop.append(i**2)
end_time = time.perf_counter()
time2 = end_time - start_time
print(f"List comprehension: {time1:.6f} seconds")
print(f"Regular loop: {time2:.6f} seconds")
print(f"Difference: {abs(time1 - time2):.6f} seconds")
List comprehension: 0.001245 seconds Regular loop: 0.001876 seconds Difference: 0.000631 seconds
Key Points
- High Resolution: Provides the highest available resolution for short duration measurements
- Monotonic: The reference point is undefined, but consecutive calls are guaranteed to be monotonic
-
Includes Sleep: Unlike
process_time(), it includes time elapsed during sleep - Best for Benchmarking: Ideal for measuring elapsed time in performance testing
Conclusion
The time.perf_counter() function is the most accurate way to measure execution time in Python. Use it for benchmarking code performance and measuring elapsed time with the highest available resolution.
