1

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

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

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

4

2 回答 2

3

我运行

python program with -m cProfile

例子:

python -m cProfile <myprogram.py>

这将需要对myprogram.py

于 2019-11-30T04:03:25.100 回答
2

有几种方法。

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()
于 2015-12-02T00:10:42.323 回答