2016-10-19 6 views
0

cprofilerで1つの関数をプロファイルする方法は?Python cprofiler a function

label = process_one(signature) 

import cProfile 

label = cProfile.run(process_one(signature)) 

になるが、それはうまくいきませんでした:/

+0

私はあなたの質問をGoogleで検索し、それに答えて、このリンクを見つけます。https://ジュリアン。 danjou.info/blog/2015/guide-to-python-profiling-cprofile-concrete-case-carbonara – sisanared

答えて

1

あなたはいくつかのデコラこれは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

+0

@Fractaleこの回答はあなたを助けますか?もしそうなら、適切な印を付けてください。 –

関連する問題