Profiling python functions by line_profiler

Privalov Vladimir
1 min readJan 15, 2021

We can easily profile functions in Python using line_profiler package. This package profiling functions simply using decorator around these functions.

First Install package:

pip install line_profiler

And add decorator @profile around function

@profile                                                                                                                                        
def fact(n):
if n == 0: return 1
elif n == 1: return 1

Then use profiler. First create dump file for out test.py

kernprof --line-by-line test.py

This command will create file test.py.lprof

Now run profiler

python -m line_profiler test.py.lprof

Output

Timer unit: 1e-06 sTotal time: 1e-05 s
File: test.py
Function: fact at line 1
Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 @profile
2 def fact(n):
3 3 3.0 1.0 30.0 if n == 0: return 1
4 3 2.0 0.7 20.0 elif n == 1: return 1
5 2 5.0 2.5 50.0 else: return n * fact(n-1)

This prints statistics for executing every line in the function call.

That’s it.

--

--