Measuring runtime in Python (line_profiler)
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
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:
General syntax to get line-by-line runtime of a function call:
%lprun -f function_name function_call(arg1, arg2 ...)
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_profilerdef add_dollar(nums):prices = ['$'+ str(price) for price in nums]return pricesnums = [1, 2, 3, 4]%lprun -f add_dollar add_dollar(nums)Timer unit: 1e-06 sTotal time: 1.2e-05 sFile: <ipython-input-6-0ebfeb8e89f9>Function: add_dollar at line 1Line # 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:
The unit of time used for measurement
The line number
Number of times the line of code was executed
Total time the line took to execute.
The time taken for executing the line once. Hits / Time
Time spent executing that line of code as a percentage of time spent for executing entire function.
The source code for each line