如何使用cProfile模块对python中的每个函数进行计时



我有一个Python程序,它接受几个命令行参数,并在几个函数中使用它们。如何使用cProfile(在我的代码中)来获取每个函数的运行时间?(我仍然希望程序完成后能正常运行)。然而,我不知道如何,例如,我不能使用

cProfile.run('loadBMPImage(sys.argv[1])')

以测试函数loadBMPImage的运行时间。我不能使用sys.argv[1]作为参数。如果每个函数都依赖于命令行参数,我知道如何使用cProfile来测试每个函数的运行时间并打印到stdout吗?此外,cProfile必须集成到代码本身中。感谢

有几种方法。

import cProfile
import pstats
import sys

def function(n):
    a = 1
    for i in range(n):
        a += 1
    return a

第一个是使用一个简单的包装器runctx(),它允许您为执行的字符串指定全局和本地。在下面的示例中,我使用globals()来传递function对象,使用locals来传递参数,但当然,它可以以不同的方式排列。

def profile1():
    cProfile.runctx("function(n)", globals(), dict(n=int(sys.argv[1])), filename='test')
    return pstats.Stats('test')

不需要使用exec的更好方法是使用Profile类。通过这种方式,您可以只评测一段常规代码:

def profile2():
    pr = cProfile.Profile()
    pr.enable()
    function(int(sys.argv[1]))
    pr.disable()
    return pstats.Stats(pr)

为了完整起见,使示例可运行

if __name__ == '__main__':
    profile1().print_stats()
    profile2().print_stats()

我运行

python program with -m cProfile

示例:

python -m cProfile <myprogram.py>

这将需要对myprogram.py 进行零更改

我的2便士。

当运行python3-m cProfile yourprogram.py时,cwd和sys.argv[0]似乎已更改(i没有彻底检查),从而伤害了程序的隐含上下文,尤其是在它通常作为可执行文件运行。

因此,我建议你把原件包起来函数中的代码,并通过cProfile.run()运行它,即使您的代码发生了一些更改。

def yourfunction():
    import sys
    print (sys.argv)
import cProfile
cProfile.run("yourfunction()")

祝你好运!

最新更新