DEV Community

Azad Kshitij
Azad Kshitij

Posted on • Edited on

Data Science: %%timeit in python

Youtube Short

In Python, the %%timeit magic command is a handy tool for measuring the execution time of small bits of code. It can be used in interactive environments like Jupyter notebooks.

To use %%timeit, you simply place it at the beginning of a cell in a Jupyter notebook, followed by the code you want to measure the execution time of. %%timeit will then run the code multiple times and return the fastest run time among all the runs.

timeit code

The output shows the time it took to run the code in microseconds, as well as the mean and standard deviation of the run times across multiple runs.

cell output

The number of runs and loops can be adjusted by passing arguments to %%timeit.

timeit with arguments

In this example, %%timeit will run the code 10 times and do 100 loops per run.

Argument Result

%%timeit is a useful tool for identifying performance bottlenecks in your code and optimizing the most heavily used sections. It can be especially helpful for comparing the performance of different algorithms or implementations.

Top comments (0)