2013-09-16 6 views
13

私は楽器今line_profilerまたはcprofileのようなもので、これらのテストのいずれかに希望pytestテストでline_profilerを実行できますか?

py.test --durations=10 

といくつかの実行時間の長いpytestテストを同定しました。 pytestのセットアップやティアダウンが遅いものの一部になる可能性があるので、私は実際にテスト自体からプロファイルデータを取得したいと思っています。

しかし、通常、line_profilerやcprofileがどのように関わっているかを考えれば、pytestでそれらを動作させる方法は私には分かりません。 py.testコードで動作するようにcProfileline_profilerを取得するには

答えて

6

は、私は2つのことをしました:

  1. は、それが実行可能で作られたpytest.mainの呼び出し()、とpy.testテストコードを拡張しました

    # pytest_test.py: 
    @profile # for line_profiler only 
    def test_example(): 
        x = 3**32 
        assert x == 1853020188851841 
    
    # for profiling with cProfile and line_profiler 
    import pytest 
    pytest.main(__file__) 
    

    今、あなたは他のツールを使用して、メインドライバーとしてpy.testせずにこのテストを実行することができます:

    メインドライバとしてPythonインタプリタ

    def pytest_funcarg__foo(request): 
        return foo(request) 
    
    @profile 
    def foo(request): 
    ... 
    

$ kernprof.py -l pytest_test.py 
$ python -m line_profiler pytest_test.py.lprof 

または

$ python -m cProfile pytest_test.py 
  • プロファイルにpy.test固有の機能は、このようなline_profilerpytest_funcarg*()ように私はpy.testline_profiler間の混乱を避けるために2つにそれらを分割します同じ方法がmemory_profilerで機能します。ランはこのようpytest

  • 18

    python -m cProfile -o profile $(which py.test) 
    

    をあなたも、オプションの引数に渡すことができます。

    python -m cProfile -o profile $(which py.test) \ 
        tests/worker/test_tasks.py -s campaigns 
    

    これはあなたの現在のディレクトリにprofileというバイナリファイルを作成します。これはpstatsで解析することができます。

    import pstats 
    p = pstats.Stats('profile') 
    p.strip_dirs() 
    p.sort_stats('cumtime') 
    p.print_stats(50) 
    

    これは、累積期間が最も長い50行を出力します。

    +0

    私はこれをWindows上で動作させようとしました。 "py.test.exeバイナリへの絶対パスを与えようとしましたが、別のエラーが出ます:" TypeError:compile() Windowsでコマンドラインから実行する方法を教えてください。 – Kanguros

    +0

    コマンドラインから: '' python -c '' import from "' 'python -c ''を実行すると、テストモジュールにpytest.mainを追加してプロファイリングを実行できます。 print_stats(50) "' 'pstats.stats( 'profile').strip_dirs()。sort_stats( 'cumtime')。 – jwhitlock

    関連する問題