search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Outline
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 (line_profiler)

schedule Aug 10, 2023
Last updated
local_offer
Python
Tags
tocTable of Contents
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

We can use the line_profiler package in Python to perform a line-by-line analysis of runtime of a function call. If you would simply like to measure the runtime of a single line or block of code refer to %timeit.

If you haven't installed the package you will first need to do so:

pip install line_profiler

Next we need to load the line_profiler package into our session:

%load_ext line_profiler

General syntax to get line-by-line runtime of a function call:

%lprun -f function_name function_call(arg1, arg2 ...)

Examples

Here is a function to add '$' to each element of a list:

def add_dollar(nums):
prices = ['$'+ str(price) for price in nums]
return prices

To measure the runtime of the function call:

%load_ext line_profiler

def add_dollar(nums):
prices = ['$'+ str(price) for price in nums]
return prices

nums = [1, 2, 3, 4]

%lprun -f add_dollar add_dollar(nums)
Timer unit: 1e-06 s
Total time: 1.2e-05 s
File: <ipython-input-6-0ebfeb8e89f9>
Function: add_dollar at line 1
Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 def add_dollar(nums):
2 1 11.0 11.0 91.7 prices = ['$'+ str(price) for price in nums]
3 1 1.0 1.0 8.3 return prices

Interpreting the results:

Header

Explanation

Timer unit

The unit of time used for measurement

Line #

The line number

Hits

Number of times the line of code was executed

Time

Total time the line took to execute.

Per Hit

The time taken for executing the line once. Hits / Time

% Time

Time spent executing that line of code as a percentage of time spent for executing entire function.

Line Contents

The source code for each line

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
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!