我怎样才能在Python或IPython中只分析我的代码?

时间:2021-03-28 20:48:32

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?

我熟悉IPython中使用Python配置文件模块的%prun magic命令。但是,我只想描述我的代码。也就是说,我想看看哪些是我的Python代码中最慢的行,而不是深埋在我正在使用的一些外部包中的行,这些行经常被调用,因此似乎占用了大部分时间。我怎样才能做到这一点?

2 个解决方案

#1


1  

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

虽然line_profiler工作,但它增加了很多开销,你需要将@profile放在一起。

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

您可以通过各种方式对%prun的输出进行排序。其中一个是按模块名称:

%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.

因此,相应地选择文件名,例如以下划线开头,会将文件放在列表%prun show的开头。

#2


1  

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

基于谷歌搜索似乎line_profiler似乎是答案: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()

#1


1  

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

虽然line_profiler工作,但它增加了很多开销,你需要将@profile放在一起。

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

您可以通过各种方式对%prun的输出进行排序。其中一个是按模块名称:

%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.

因此,相应地选择文件名,例如以下划线开头,会将文件放在列表%prun show的开头。

#2


1  

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

基于谷歌搜索似乎line_profiler似乎是答案: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()