首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python函数

Python函数
EN

Stack Overflow用户
提问于 2016-10-19 13:21:22
回答 2查看 2.5K关注 0票数 0

如何使用cprofiler来分析一个函数?

代码语言:javascript
复制
label = process_one(signature)

成为

代码语言:javascript
复制
import cProfile

label = cProfile.run(process_one(signature))

但是它没有起作用

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-10-19 14:21:48

您可以编写一些装饰器,这将有助于使用cProfile对任何函数进行分析。这可以帮助我在需要的时候快速获得统计数据。

代码语言:javascript
复制
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))

样本输出:

代码语言:javascript
复制
         7 function calls in 0.013 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.013    0.013 qprofiler.py:29(process_one)
        1    0.000    0.000    0.013    0.013 commands.py:48(getoutput)
        1    0.000    0.000    0.013    0.013 commands.py:56(getstatusoutput)
        1    0.013    0.013    0.013    0.013 {method 'read' of 'file' objects}
        1    0.000    0.000    0.000    0.000 {posix.popen}
        1    0.000    0.000    0.000    0.000 {method 'close' of 'file' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Linux chronin 4.4.0-42-generic #62-Ubuntu SMP Fri Oct 7 23:11:45 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

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

票数 4
EN

Stack Overflow用户

发布于 2016-10-19 13:55:36

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40132630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档