了解方法调用的cProfile和pstats输出

时间:2016-03-17 13:54:06

标签: python class methods profiling

我正在使用this question答案中描述的Python cProfile来优化我的代码。我发现在函数内调用特定方法(每秒多次)会花费比我预期更多的时间。我的代码结构可以总结如下:

while(IShouldBeRunning):
    d = object.intersection(args)

其中object是类的实例,intersection是该类的方法,该类位于单独的文件geometries.py中。我用两种不同的方式测量了调用此方法所需的时间。首先,我测量了上面显示的while循环内的时间:

while(IShouldBeRunning):
    pr = cProfile.Profile()
    pr.enable()

    d = object.intersection(args)

    pr.disable()
    break

接下来,我在intersection方法中测量了它:

def intersection(self, args):

    pr = cProfile.Profile()
    pr.enable()

    *some computation*

    pr.disable()

pstats的相应输出如下所示:

12 function calls in 0.006 seconds

Ordered by: cumulative time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.005    0.005    0.006    0.006 geometries.py:11(intersection)
    1    0.000    0.000    0.001    0.001 fromnumeric.py:1631(sum)
    1    0.000    0.000    0.001    0.001 _methods.py:31(_sum)
    1    0.001    0.001    0.001    0.001 {method 'reduce' of 'numpy.ufunc' objects}
    2    0.000    0.000    0.000    0.000 {built-in method array}
    1    0.000    0.000    0.000    0.000 twodim_base.py:83(flipud)
    ...


11 function calls in 0.001 seconds

Ordered by: cumulative time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.001    0.001 fromnumeric.py:1631(sum)
    1    0.000    0.000    0.001    0.001 _methods.py:31(_sum)
    1    0.001    0.001    0.001    0.001 {method 'reduce' of 'numpy.ufunc' objects}
    2    0.000    0.000    0.000    0.000 {built-in method array}
    1    0.000    0.000    0.000    0.000 twodim_base.py:83(flipud)
    ...

intersection方法中的代码似乎没有花费太多时间来运行,但是对此方法的调用需要更多时间。我能正确地解释这个吗?如果是这样,为什么调用此方法会产生这样的开销,是否可以减少它?

0 个答案:

没有答案