How to use timeit to profile Python code

With Python’s built-in timeit module, you can measure the performance of your functions or lines of code in one easy step

How to use timeit to profile Python code

By design, Python puts convenience, readability, and ease of use ahead of performance. But that doesn’t mean you should settle for slow Python code. There is probably something you can do to speed it up.

Among the tools available for profiling the performance of Python code, the simplest is the timeit module. timeit is used to measure the speed of small snippets of code — a few lines, a function — by executing the code thousands or even millions of times and reporting how long those executions took to complete.

timeit is most useful for comparing two or three different ways to do something and seeing which is the fastest. For instance, a loop that runs for thousands of iterations is a common Python bottleneck. If you can find a way to speed up the implementation of that loop — say, by using Python built-ins instead of handwritten code — you could get a measurable performance improvement.

A simple Python timeit example

To continue reading this article register now

How to choose a low-code development platform