【问题标题】:profiling numpy with cProfile not giving useful results使用 cProfile 分析 numpy 没有给出有用的结果
【发布时间】:2013-12-06 21:39:34
【问题描述】:

这段代码:

import numpy as np
import cProfile

shp = (1000,1000)
a = np.ones(shp)
o = np.zeros(shp)

def main():
    np.divide(a,1,o)
    for i in xrange(20):
        np.multiply(a,2,o)
        np.add(a,1,o)

cProfile.run('main()')

仅打印:

         3 function calls in 0.269 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.269    0.269 <string>:1(<module>)
        1    0.269    0.269    0.269    0.269 testprof.py:8(main)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}

我可以让 cProfile 与 numpy 一起工作,告诉我它对各种 np.* 调用进行了多少次调用,以及每次调用花费了多少时间?

编辑

按照 hpaulj 的建议单独包装每个 numpy 函数太麻烦了,所以我正在尝试这样的方法来临时包装许多或所有感兴趣的函数:

def wrapper(f, fn):
    def ff(*args, **kwargs):
        return f(*args, **kwargs)
    ff.__name__ = fn
    ff.func_name = fn
    return ff

for fn in 'divide add multiply'.split():
    f = getattr(np, fn)
    setattr(np, fn, wrapper(f, fn))

但 cProfile 仍将 all 称为ff

【问题讨论】:

    标签: numpy cprofile


    【解决方案1】:

    如何将相关调用封装在 Python 函数中?

    def mul(*args):
        np.multiply(*args)
    def add(*args):
        np.add(*args)
    
    def main():
        np.divide(a,1,o)
        for i in xrange(20):
            mul(a,2,o)
            add(a,1,o)
    

    这基本上是这个 SO 线程中关于改进分析粒度的想法 - 它分析函数调用,而不是行。

    Does effective Cython cProfiling imply writing many sub functions?

    【讨论】:

    • 点,但这对于我的真实分析来说太麻烦了。我尝试了一些自动包装,但失败了(如果需要,请参阅编辑)我什至尝试过这个:code.activestate.com/recipes/… 但那里也有问题。
    猜你喜欢
    • 2018-12-08
    • 2018-06-02
    • 2012-06-23
    • 2017-08-25
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2018-11-30
    • 2014-03-12
    相关资源
    最近更新 更多