Measuring runtime in Python (timeit)
Start your free 7-days trial now!
We can measure how long it takes to run a piece of code in Python using the magic command
%timeit is suited for measuring the runtime for short blocks of code.
Magic commands are enhanced capabilities on top of normal Python syntax and they are prefixed by a "
Single line runtime
To time how long it takes to run a single line of code:
%timeit nums = 36.8 ns ± 2.73 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit runs the line of code multiple times and takes the average.
runs: number of iterations to use to estimate runtime
loop: how many times code should be executed per run
To specify the number of runs and loops to use:
%timeit -r1 -n10 nums =  #r is runs, n is loops114 ns ± 0 ns per loop (mean ± std. dev. of 1 run, 10 loops each)
Multiple line runtime
To measure runtime for multiple lines of code:
%%timeitfor x in range(5):x +=1534 ns ± 18.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Notice how we use two percentage marks
%% in front of
timeit when using for multiple lines.
Save output to a variable
To save the output to a variable we can use
runtime = %timeit -o nums = 37.1 ns ± 2.61 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
To access attributes of the variable:
runtime.timings #time for each runruntime.best #best time for all runsruntime.worst #worst time for all runs