Predictive Hacks

How to Measure the Execution Time of a Python Script in Jupyter Notebook

%timeit is a magic command in Jupyter notebooks that allows you to measure the execution time of a piece of code. It works by running the code multiple times and taking the best run time.

Here’s an example of how to use %timeit:

%timeit sum(range(100))

This will execute the sum function with the range [0, 1, 2, ..., 99] and return the best time out of a few runs. The output will look something like this:

779 ns ± 15.6 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

You can also use %timeit with an optional argument to specify the number of runs and the length of each run. For example:

%timeit -r3 -n1000 sum(range(100))

This will execute the sum function with the range [0, 1, 2, ..., 99] 1000 times with 3 repeats, and return the best time out of the 3 repeats. The output will look something like this:

3.21 µs ± 584 ns per loop (mean ± std. dev. of 3 runs, 1,000 loops each)

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s