Benchmark code using a high-resolution performance counter.
How It Works
time.perf_counter() measures a high-resolution elapsed duration and includes time spent sleeping. Its origin is arbitrary; subtract two readings to get a meaningful elapsed result.
Step-by-Step Example
import time
start_counter = time.perf_counter()
squared_values = [number * number for number in range(10000)]
end_counter = time.perf_counter()
print(len(squared_values))
print(end_counter >= start_counter)
Understanding the Example
- The expression 'time.perf_counter()' supplies the value stored as 'start_counter'. This value is then used or checked by the later statements.
- The expression '[number * number for number in range(10000)]' supplies the value stored as 'squared_values'. This value is then used or checked by the later statements.
Run the complete example as written, then inspect the displayed result. The values returned by the operation are more important than simply seeing the script finish.
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
Use timeit for careful small-operation benchmarks.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Reporting a single tiny timing result as definitive performance evidence without repeated trials.
- Compare two sorting approaches across multiple performance runs.
Key Takeaways
- Benchmark code using a high-resolution performance counter.
- time.perf_counter() measures a high-resolution elapsed duration and includes time spent sleeping.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.