Last updated: Apr 10, 2024
Reading time·3 min
%timeit
time
moduletime.perf_counter()
to measure cell execution timeUse the %time
magic command to measure cell execution time in Jupyter
Notebook.
The command measures the execution time of a Python statement or expression.
%%time for i in range(5000000): i * i
The %time
magic command times the execution of a Python statement or
expression.
The command prints the CPU and wall clock times and the value of the expression (if any) is returned.
The time needed for Python to compile the given expression is reported if it
takes more than 0.1s
.
The %time
magic command provides basic timing functionality.
For more fine-grained control, use the %timeit
command.
%timeit
The %timeit
magic command prints the time execution of a Python statement or
expression.
%%timeit for i in range(5000000): i * i
The %timeit
command runs the statement in the cell multiple times and returns
the average runtime for some statements and the standard deviation.
time
moduleYou can also use the time module to measure cell execution time in Jupyter Notebook.
import time start_time = time.time() for i in range(5000000): i * i print(time.time() - start_time)
The time.time() method returns the time in seconds since the epoch as a floating point number.
We call the method before the code starts executing and store the result in a variable.
As shown in the screenshot, the code in the example is executed in 388ms.
You might have to use the round() function if you want to round the result to N digits after the decimal.
import time start_time = time.time() for i in range(5000000): i * i print(round(time.time() - start_time, 2))
The round
function takes the following 2 parameters:
Name | Description |
---|---|
number | the number to round to ndigits precision after the decimal |
ndigits | the number of digits after the decimal, the number should have after the operation (optional) |
The code sample rounds the result to 2 decimal places.
time.perf_counter()
to measure cell execution timeYou can also use the time.perf_counter() method to measure cell execution time.
import time start_time = time.perf_counter() for i in range(5000000): i * i print(time.perf_counter() - start_time)
The time.perf_counter()
method returns the value (in fractional seconds) of a
performance counter.
The method includes time elapsed during sleep and is system-wide.
There is also a time.process_time() method that does not include time elapsed during sleep.
import time start_time = time.process_time() for i in range(5000000): i * i print(time.process_time() - start_time)
You can also use the time.monotonic() method in a similar way.
import time start_time = time.monotonic() for i in range(5000000): i * i print(time.monotonic() - start_time)
The time.monotonic()
method returns the value of a monotonic clock in
fractional seconds.
The clock is not affected by the system clock updates.
You can learn more about the related topics by checking out the following tutorials: