Skip to main content
 首页 » 编程设计

python之line_profiler 未按预期工作

2025年05月04日9insus

尝试将 line_profiler 用作 API。正在关注their docs和 this tutorial (向下滚动到行分析),我得到了一个用于分析一些 numpy ufunc 的极简测试用例:

import numpy as np 
import line_profiler 
import time 
 
shp = (1000,1000) 
a = np.ones(shp) 
o = np.zeros(shp) 
 
def main(): 
    t = time.time() 
    np.divide(a,1,o) 
    for i in xrange(200): 
        np.multiply(a,2,o) 
        np.add(a,1,o) 
    print 'duration', time.time()-t 
 
profiler = line_profiler.LineProfiler() 
profiler.add_function(main) 
main() 
profiler.print_stats() 

我在 stdout 中得到这个,它表明 main 运行了,但没有被分析:

duration 2.6779999733 
Timer unit: 5.59936e-07 s 
 
File: testprof.py 
Function: main at line 9 
Total time: 0 s 
 
Line #      Hits         Time  Per Hit   % Time  Line Contents 
============================================================== 
     9                                           def main(): 
    10                                               t = time.time() 
    11                                               np.divide(a,1,o) 
    12                                               for i in xrange(200): 
    13                                                   np.multiply(a,2,o) 
    14                                                   np.add(a,1,o) 
    15                                               print 'duration', time.time 
()-t 

我是 line_profiler 的新手。看我的other q如果好奇为什么我不使用 cProfile。

请您参考如下方法:

尝试添加

profiler.enable_by_count()

之前

main()