DEV Community

Azad Kshitij
Azad Kshitij

Posted on • Edited on

1

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay