Python perf_counter()
The perf_counter() function returns a floating-point number representing a high-resolution timer value (in seconds) at the moment of the call, and is commonly used to benchmark code by measuring the time taken to execute a piece of code.
Syntax
time.perf_counter()
Parameters:
The function takes no arguments.
Return value:
Returns a float representing the current value of a high-resolution performance counter in seconds.
Example 1
This example shows how to call perf_counter() to get the current high-resolution timer value:
import timeprint(time.perf_counter())
A possible output of this code is:
5003.666789873
Importing perf_counter() from time:
from time import perf_counterprint(perf_counter())
A possible outcome of this code is:
1780743.368374651
Example 2
Here, two perf_counter() calls are placed around sleep() which adds a 5-second delay in the execution right after the first method call:
from time import perf_counter, sleep# record current time before delaystart = perf_counter()print('Time before sleep():', start)sleep(5) # pause for 5 seconds# record current time after delayend = perf_counter()print('Time after sleep():', end)# calculate elapsed time between both callselapsed_time = end - startprint('Elapsed time in seconds:', elapsed_time)
The output of this code is:
Time before sleep(): 1781952.36727265Time after sleep(): 1781957.367474534Elapsed time in seconds: 5.000201884191483
Codebyte Example
The following program shows two ways to search for an element in a sorted integer list. Both solutions are written in separate functions, and pairs of perf_counter() calls are used to track the time taken to execute each function:
Note: The actual numbers will vary each time you run the code, since they represent the current internal timer value, not absolute wall-clock time.
Ideally, with a large nums list the binary search function should take half as much time as the linear search function.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours