我正在对我的代码做一些分析,并尽可能地优化它。但我注意到,特定函数的总累积时间有时不会加起来。所以我不确定哪种功能是罪魁祸首。
为了让这更简单,我在下面创建了一个简单的例子--它没有真正做任何事情。
L = [1,2,3,4,5]
class MyObj:
__slots__ = "a", "b"
def __init__(self, a="", b=""):
self.a = a
self.b = b
def get_top():
return L[0]
def revert(x):
return -x
def check():
if True:
return True
else:
return False
def main(x):
if check():
p = revert(x)
q = get_top()
o = MyObj(a=p, b=q)
else:
o = MyObj()
for x in range(10_000_000):
main(x)如果我使用pypy3执行此操作( python3也会执行相同的场景),并使用代码:
python -m cProfile test.py我得到的东西是:
50000005 function calls in 1.895 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.522 0.522 1.895 1.895 test0.py:1(<module>)
10000000 0.180 0.000 0.180 0.000 test0.py:12(get_top)
10000000 0.153 0.000 0.153 0.000 test0.py:16(revert)
10000000 0.140 0.000 0.140 0.000 test0.py:20(check)
10000000 0.746 0.000 1.374 0.000 test0.py:27(main)
1 0.000 0.000 0.000 0.000 test0.py:4(MyObj)
10000000 0.156 0.000 0.156 0.000 test0.py:7(__init__)
1 0.000 0.000 0.000 0.000 {built-in function __build_class__}
1 0.000 0.000 1.895 1.895 {built-in function exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}如您所见,主计算时间为1.374次,累计时间为0.746次,但是当将调用的函数相加时,它将小于这个数字。这是不是总不能算数?我只是想知道,如果每个函数的时间都不准确,我如何才能分辨出需要一段时间的函数--假设函数是由多个函数组成的main()。
发布于 2022-04-12 04:26:35
有一些关于分析PyPy 这里的提示。通常,像cprofile这样的确定性分析器会破坏JIT,因此不建议使用PyPy进行分析。当分析器每隔X毫秒对程序堆栈进行采样时,统计方法会更好。在使用JIT时,分析和优化是很难解决的问题,因为通常情况不会加起来:解释器本身存在很难度量的开销。
https://stackoverflow.com/questions/71822317
复制相似问题