Profiling python functions by line_profiler

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

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

Then use profiler. First create dump file for out

kernprof --line-by-line

This command will create file

Now run profiler

python -m line_profiler


Timer unit: 1e-06 sTotal time: 1e-05 s
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.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store