Low Orbit Flux Logo 2 D

Python How To Time Code

It is relatively common to want to know how long it takes for a section of code to run. When working with Python we can check the time before and after performing a specific task. We can then check the difference between those two values to see how long it took.

The following example shows how we might time a piece of code. We use the time.time() function to do this.

import time 

before = time.time()
after = time.time() 

total = t1-t0

Using timeit

You can also use the timeit library to time code. This is actually kind of nice since it also lets you specify how many times to execute the code that you pass it. You would store a piece of code as a string and pass it to the time.timeit() function.

Here is how you could time a really simple expression:


Here we time the sleep() function and we tell it to run 10 times.

timeit.timeit("time.sleep(2)", number=10)

Python How to Time an Entire Script

You can also test how long it takes to run an entire script from the command line like this. This works on Linux and probably also on Mac OS and BSD systems.

time python3 test.py 

This basically just uses the Linux time command.