Skip to content

How to measure the elapsed time in Python

Learn how you can measure elapsed time in Python with different methods.


Learn how you can measure elapsed time in Python.

We will look at those different methods:

  • Use time.time()
  • Use timeit.default_timer()
  • Use timeit from the command line
  • Use timeit in code
  • Use timeit in Jupyer Notebook Cells
  • Use a decorator

Use time.time()

You can use time.time() to create the current time. Then you determine the time before and after the code part you want to measure, and in the end you can subtract the time points to get the elapsed time:

import time

start = time.time()
# your code...
end = time.time()
print(end - start) # time in seconds

Use timeit.default_timer()

The default_timer provides the best clock available on your platform and version of Python automatically. It is good practice to use this instead of time.time():

from timeit import default_timer as timer

start = timer()
# your code...
end = timer()
print(end - start) # time in seconds

Use timeit from the command line

The timeit module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one.

From the command line you can use it like this:

 python -m timeit '"-".join(str(n) for n in range(100))'

The output could look like this:

50000 loops, best of 5: 7.83 usec per loop

If you want a specific number of loops, you can use the -n option:

 python -m timeit -n 100  '"-".join(str(n) for n in range(100))'
100 loops, best of 5: 9.28 usec per loop

Use timeit in code

You can also use it in your code. The function needs a callable object, so if you want to measure a simple calculation you can combine it with a lambda expression:

import timeit

timeit.timeit(lambda: "-".join(map(str, range(100))), number=1000)

Use timeit in Jupyer Notebook Cells

If you work with Notebooks, you can use the magic command %timeit to measure the time. The rest works the same way as if used from the command line:

# jupyter cell
def do_something():
    for i in range(100): i * i

%timeit -n 1000 do_something()

Output:

2.26 µs ± 82.5 ns per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

Use a decorator to measure the time of a function

If you want to measure the time for multiple parts in your code and don't want to repeat the above code snippets every time, you can write a decorator that simply wraps the function and measures the execution time:

from timeit import default_timer as timer

def timer_func(func):
    def wrapper(*args, **kwargs):
        t1 = timer()
        result = func(*args, **kwargs)
        t2 = timer()
        print(f'{func.__name__}() executed in {(t2-t1):.6f}s')
        return result
    return wrapper

Then you can apply this decorator to all functions you want to time:

@timer_func
def do_something():
    for i in range(1000000): i * i

do_something()
# do_something() executed in 0.030401s

You can learn more about Decorators in this article.


FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*


Python Problem-Solving Bootcamp

🚀 Solve 42 programming puzzles over the course of 21 days: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏