how to measure running time of algorithms in python
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Measuring algorithm runtime in Python is easy to start and easy to do badly. A single timing often reflects background noise, cache state, or unlucky input more than the algorithm itself. Good measurements come from using the right clock, running repeated trials, and keeping the comparison conditions stable.
Use the Right Timer for Elapsed Time
For wall-clock benchmarking, time.perf_counter() is the standard choice. It is monotonic and has better resolution than older timing functions.
This is fine for quick checks, but one run is not enough to support any serious conclusion.
Repeat the Measurement and Report Robust Statistics
Operating system scheduling, Python memory management, and background processes introduce noise. Run the same benchmark many times and report at least the median.
The median is often more informative than the mean because it is less affected by occasional slow runs.
Use timeit for Small, Focused Benchmarks
When the code under test is short, timeit is a better tool than hand-written loops. It reduces measurement boilerplate and is designed for repeat execution.
timeit is especially useful for comparing small expressions or verifying whether a local refactor changed a hot code path.
Compare Algorithms on Equivalent Inputs
A fair comparison means each algorithm sees the same logical input. That matters most for in-place algorithms, because the first run can mutate the data and make later runs look faster.
Copying the input before each run avoids accidental bias.
Measure Across Input Sizes and Shapes
Runtime analysis is not only about one absolute number. The interesting question is how the runtime grows as the input grows and how the algorithm reacts to different data distributions.
An algorithm may look acceptable on nearly sorted input and collapse on reversed or random input. If production data has a specific shape, benchmark that shape explicitly.
Use Profiling When the Benchmark Is Too Coarse
Timing only tells you how long the whole operation took. It does not tell you where the time went. If you need to optimize real code, pair timing with profiling.
This helps you avoid spending time optimizing code that is not actually the bottleneck.
Control the Environment Enough to Trust the Result
For serious measurements, reduce avoidable noise. Run on a consistent power profile, close heavy applications, avoid timing through a debugger, and record the Python version. If you are comparing runs over time in CI or across teammates, note the CPU and operating system as well.
Do not chase false precision. Reporting many decimal places does not make a noisy benchmark more reliable. Good methodology matters more than fine-grained formatting.
Common Pitfalls
A common mistake is reporting one benchmark result as if it were definitive. Repeated trials are required if you want a trustworthy number.
Another issue is benchmarking unrealistic toy inputs. If production data is mostly sorted, mostly random, or much larger than the test input, your benchmark should reflect that reality.
Developers also accidentally measure setup work, logging, or printing instead of the algorithm itself. Keep the timed section focused on the computation you actually care about.
Finally, many comparisons are invalid because one function mutates the input and the next function receives an already-processed version. Always copy shared benchmark inputs when mutation is possible.
Summary
- Use
time.perf_counter()for elapsed-time measurements. - Run repeated trials and report median or similar robust statistics.
- Use
timeitfor short microbenchmarks andcProfilefor hotspot analysis. - Compare algorithms on equivalent inputs and across realistic sizes.
- Treat benchmark setup as part of the engineering work, not as an afterthought.
Related reading
- How to merge multiple rectangles into one polygon
- How to merge two BST's efficiently?
- How to merge two sorted arrays into a sorted array?
- How to merge two sorted arrays into a sorted array?
- How to measure server response time for Python requests POST-request
- How to measure service methods using spring boot 2 and micrometer
- how to measure the accuracy of knn classifier in python
- How to merge a transparent png image with another image using PIL

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.