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