How to use timeit module
Measure execution time of your Python code using timeit.timeit()
. Pass your code in a string, and specify iterations with number
:
The above measures the time to execute sum(range(100))
1000 times. Dial up number
for better precision.
Precision timing of functions
Handle function-specific timing by directly invoking timeit.Timer()
. Use functools.partial
to curb the timer's impact:
Here, partial
helps to lower the timing overhead.
Prepping the stage with setup
setup
lets you reset starting conditions to keep data states from messing with results. It's a lifesaver for tests like in-place sorting:
Juggling IPython and command-line integration
In IPython, %timeit
eases syntax:
On the command line, use -m timeit
:
The -s
flag sets initial conditions, ensuring consistent tests.
Running a function efficiency contest
Assess various implementations by comparing their time efficiency. It's like a code beauty contest, with beauty being superlative performance:
Dive deeper, go further
For advanced benchmarking:
- Play out multiple suite runs with
timeit.repeat
and fix eyes on the shortest time. - Scramble data in between runs to dodge timing biases.
- Learn how Python's standard library's Timsort fares on partially ordered data.
- Deep-dive into the documentation for a more profound grasp on
timeit
.
Was this article helpful?