Python .perf_counter_ns()
.perf_counter_ns() is a function from the time module that returns a high-resolution timer value in nanoseconds as an integer.
Syntax
time.perf_counter_ns()
Parameters:
The .perf_counter_ns() function takes no arguments.
Return value:
Returns the value of a high-resolution performance counter in nanoseconds as an integer.
Example 1
In this example, .perf_counter_ns() from the time module is used to measure elapsed time for a block of code by taking timestamps before and after execution and calculating the difference:
import timestart = time.perf_counter_ns() # start timerend = time.perf_counter_ns() # end timerprint("Elapsed:", end - start, "nanoseconds")
A sample output for this code is:
Elapsed: 800 nanoseconds
Example 2
This example shows how to use .perf_counter_ns() to benchmark even small tasks very precisely:
import timeimport random# Create a random list of numbersnumbers = [random.randint(1, 1000000) for _ in range(100000)]# Start timerstart = time.perf_counter_ns()# Code we want to measurenumbers.sort()# End timerend = time.perf_counter_ns()# Calculate elapsed timeelapsed_ns = end - startprint(f"Sorting took {elapsed_ns} nanoseconds ({elapsed_ns / 1e6:.3f} ms)")
A sample output of this code is:
Sorting took 20045800 nanoseconds (20.046 ms)
This code generates a large list of random numbers, sorts it, and calculates the elapsed time by subtracting the start timestamp from the end timestamp, giving a precise measurement in nanoseconds (and milliseconds for readability).
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