【问题标题】:Can I run line_profiler over a pytest test?我可以通过 pytest 测试运行 line_profiler 吗?
【发布时间】:2013-09-20 17:36:31
【问题描述】:

我已经用

确定了一些长期运行的 pytest 测试
py.test --durations=10

我现在想用 line_profiler 或 cprofile 之类的东西来检测其中一个测试。我真的很想从测试本身获取配置文件数据,因为 pytest 设置或拆卸很可能是缓慢的一部分。

但是考虑到 line_profiler 或 cprofile 通常是如何参与的,我不清楚如何使它们与 pytest 一起使用。

【问题讨论】:

    标签: python pytest cprofile


    【解决方案1】:

    像这样运行 pytest:

    python3 -m cProfile -o profile -m pytest
    

    你甚至可以传入可选参数:

    python3 -m cProfile -o profile -m pytest 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 行。

    【讨论】:

    • 我试图让它在 Windows 上运行。但是如果第一个命令失败,说:“没有这样的目录文件'(哪个'”。我试图给出 py.test.exe 二进制文件的绝对路径,但我得到一个不同的错误:“TypeError:compile()没有空字节的预期字符串”。我通过在测试模块中添加一个 pytest.main 调用来运行分析。任何建议如何从 Windows 上的命令行运行它?
    • 从命令行:python -c "import pstats; pstats.Stats('profile').strip_dirs().sort_stats('cumtime').print_stats(50)"
    • python -m cProfile -o profile -m pytest 给出cProfile.py: error: no such option: -m。请改用python3 -m cProfile -o profile $(which py.test)
    【解决方案2】:

    为了让cProfileline_profilerpy.test 代码一起工作,我做了两件事:

    1. 通过调用 pytest.main() 扩展了 py.test 测试代码,这使得它可以使用 python 解释器作为主驱动程序执行:

      # 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 作为主驱动程序的情况下使用其他工具运行此测试:

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

      $ python -m cProfile pytest_test.py
      
    2. 为了分析 py.test 特定的函数,例如 pytest_funcarg*()line_profiler,我将它们一分为二以避免混淆 py.testline_profiler

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

    同样的方法适用于memory_profiler

    【讨论】:

      【解决方案3】:

      您尝试过pytest-profiling 插件吗?

      【讨论】:

      • 这是一个非常好的插件,它使分析变得非常简单,但是 AFAIK 它不做线分析
      【解决方案4】:

      我最近写了pytest-line-profiler 可能有用。它没有经过实战测试,所以请给我反馈(和帮助)。

      【讨论】:

      • 它打破了我的一些测试,即使不使用,只是安装。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 2022-01-14
      • 1970-01-01
      • 2016-03-24
      • 2019-07-17
      • 2018-01-25
      相关资源
      最近更新 更多