user1507844
user1507844

Reputation: 6573

How can I profile only my code in Python or IPython?

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?

Upvotes: 3

Views: 533

Answers (2)

user1507844
user1507844

Reputation: 6573

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()

Upvotes: 1

Mike Müller
Mike Müller

Reputation: 85612

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.

Upvotes: 1

Related Questions