代码之家  ›  专栏  ›  技术社区  ›  Fractale

Python cprofiler函数

  •  0
  • Fractale  · 技术社区  · 8 年前

    如何使用cprofiler配置一个函数?

    label = process_one(signature)
    

    成为

    import cProfile
    
    label = cProfile.run(process_one(signature))
    

    但它不起作用:/

    2 回复  |  直到 8 年前
        1
  •  4
  •   Sanket Sudake    8 年前

    您可以编写一些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))
    

             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

        2
  •  1
  •   Community CDub    8 年前

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

    还有,看看答案 https://stackoverflow.com/a/17259420/1966790