3

I'm familiar with the %prun magic command in IPython that uses the Python profile module. However, I'd like to only profile my code. That is, I'd like to see which are the slowest lines in my Python code, not the lines buried deep in some external package I'm using that get called often and therefore appear to take the most time. How can I do this?

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
user1507844
  • 5,973
  • 10
  • 38
  • 55
  • There's [*always this method*](http://stackoverflow.com/a/4299378/23771). Just ignore the lines that are not in your code. The difference between this and the line profiler is that it tells you *why* the time is being spent, not just *where*. – Mike Dunlavey Dec 20 '15 at 14:43

2 Answers2

1

Based on a little more Googling it seems that line_profiler is the answer: https://github.com/rkern/line_profiler

import line_profiler
%load_ext line_profiler

Then just

%lprun -f function_i_want_to_profile function_i_want_to_run()
user1507844
  • 5,973
  • 10
  • 38
  • 55
1

While line_profiler works, it adds a lot of overhead and you need to put @profile all over the place.

You can sort the output of %prun in all kinds of ways. One of them is by module name:

%prun -s module my_func()

So choosing your file names accordingly, like starting with an underscore, would put your files in beginning of the list %prun shows.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161