Python Line Profiler

Every time I go to use this tool, I have problems getting it to work. So I’m writing a post here for me (and for others) so that next time I come to use it, I can work it out a bit quicker.

Installation. This is covered here: . But I have an Anaconda distribution, so I would tend to use:

conda install line_profiler.

Then the trick is to call a script called to run the profiler. What it does is look for @profile decorators in your python script – so for each function you want to profile, put that decorator immediately above it.

Now, I had trouble running kernprof from inside the Spyder IDE I normally use. It doesn’t seem to be registered in the IPython console. But I can do it from the Anaconda prompt which gets installed when you install Anaconda.

So to do this, cd to the directory of the script you want to profile and run

kernprof -l

This does the profiling and saves the result into a file called

Then all you have to do then is something like:

python -m line_profiler

and you get the results in the cmd/terminal window.

If you have a script with spaces in it, do this:

kernprof -l "my script with" and

python -m line_profiler "my script with spaces .py.lprof "





And of course as soon as I figured all that out, I came across an easier way to do it. There is a Spyder IDE lin_profiler plugin:

I installed it with

conda install -c spyder-ide spyder-line-profiler

And then all you have to do to run it (after restarting Spyder) is decorate your functions you want to profile as above and then press Shift+F10 and it runs!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s