cProfile 的正确使用方法

Correct Way To Use cProfile

我想分析一下我编写的一些函数。我正在查看 cProfile 的文档,但我不明白以下两段代码之间的区别是什么(如果有的话):

import cProfile

profile = cProfile.Profile()
result = profile.runcall(func, *args, **kwargs)
profile.dump_stats('profile.stats')

import cProfile

profile = cProfile.Profile()
profile.enable()
result = func(*args, **kwargs)
profile.disable()
profile.dump_stats('profile.stats')

这两个块是等效的,还是它们做的事情略有不同?

它们几乎相同:https://github.com/python/cpython/blob/581eb3e0dc0bc0d306363c8d404ffd9988b0cc87/Lib/cProfile.py#L106

runcall 将在出现异常时停止分析,但除此之外功能相同。