search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Measuring runtime in Python (timeit)

schedule Aug 10, 2023
Last updated
local_offer
Python
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
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. %timeit is suited for measuring the runtime for short blocks of code.

NOTE

Magic commands are enhanced capabilities on top of normal Python syntax and they are prefixed by a "%" symbol.

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)
NOTE

Notice how %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 loops
114 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:

%%timeit
for x in range(5):
x +=1
534 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 -o:

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 run
runtime.best #best time for all runs
runtime.worst #worst time for all runs
robocat
Published by Arthur Yanagisawa
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
11
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!