Member-only story

Measuring Performance in Python: Optimize Your Code with %timeit

Abdulkadir Karakus
2 min readMay 20, 2024

--

Performance optimization in Python is key to developing efficient and fast applications. In this article, I will introduce you to a powerful tool for measuring code performance in Python: the `%timeit` command. With `%timeit`, you can easily find out how long specific parts of your code take to execute and make the necessary optimizations.

What is %timeit?

`%timeit` is a “magic” command available in IPython and Jupyter Notebooks, used to measure the execution time of a specific piece of code. It allows you to measure the performance of anything from single lines of code to more complex functions. By running your code multiple times, `%timeit` calculates the average execution time and standard deviation, providing reliable results.

How to Use %timeit?

Using `%timeit` is straightforward. Simply add `%timeit` before the code you want to measure. Here’s a basic example:

# Basit bir for döngüsünün çalışma süresini ölçelim
%timeit sum([i for i in range(1000)])

In this example, we measure the execution time of a loop that calculates the sum of numbers from 0 to 999 using list comprehension. `%timeit` will run this code multiple times and report the average execution time and standard…

--

--

No responses yet