Python cprofiler函数

2024-04-26 18:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用cprofiler来描述一个函数?在

label = process_one(signature)

成为

^{pr2}$

但没用:/


Tags: 函数processonelabelsignaturepr2cprofiler
2条回答

您可以编写一些decorator,这将有助于用cProfile分析任何函数。这有助于我在需要时快速获取数据。在

import cProfile
import pstats
import StringIO
import commands


def qprofile(func):
    def profiled_func(*args, **kwargs):
        if 'profile' in kwargs and kwargs['profile']:
            kwargs.pop('profile')
            profile = cProfile.Profile()
            try:
                profile.enable()
                result = func(*args, **kwargs)
                profile.disable()
                return result
            finally:
                s = StringIO.StringIO()
                ps = pstats.Stats(
                    profile, stream=s).strip_dirs(
                ).sort_stats('cumulative')
                ps.print_stats(30)
                print s.getvalue()
        else:
            result = func(*args, **kwargs)
            return result
    return profiled_func

@qprofile
def process_one(cmd):
    output = commands.getoutput(cmd)
    return output

# Function is profiled if profile=True in kwargs
print(process_one('uname -a', profile=True))

样本输出:

^{pr2}$

请参考官方文件以获取任何特定的电话参考资料, https://docs.python.org/2/library/profile.html

根据文档(https://docs.python.org/2/library/profile.html),它应该是cProfile.run('process_one(signature)')

另外,看看答案https://stackoverflow.com/a/17259420/1966790

相关问题 更多 >