gpt4 book ai didi

python - pytest:有没有办法报告测试的内存使用情况?

转载 作者:行者123 更新时间:2023-12-03 20:25:57 26 4
gpt4 key购买 nike

我检查了 pytest 文档,但找不到任何相关内容。我知道 pytest --durations=0 将打印出所有测试的运行时。有没有办法让 pytest 也打印出函数消耗的峰值内存使用量?否则,我可能只能使用下面的装饰功能。但我想知道是否有更好的方法来做到这一点。

from functools import wraps

def mem_time(func):
@wraps(func)
def wrapper(*args, **kwargs):

# Start of function
r0 = resource.getrusage(resource.RUSAGE_SELF)
t0 = datetime.datetime.now()

# Call function
status = func(*args, **kwargs)

# End of function
r1 = resource.getrusage(resource.RUSAGE_SELF)
t1 = datetime.datetime.now()

sys.stderr.write('{}: utime {} stime {} wall {}\n'.format(func.__name__,
datetime.timedelta(seconds=r1.ru_utime - r0.ru_utime),
datetime.timedelta(seconds=r1.ru_stime - r0.ru_stime),
t1 - t0))

sys.stderr.write('{}: mem {} MB ({} GB)\n'.format(func.__name__,
(r1.ru_maxrss - r0.ru_maxrss) / 1000.0,
(r1.ru_maxrss - r0.ru_maxrss) / 1000000.0))

return status

return wrapper

最佳答案

pytest 监视器 一个新的很棒的 pytest 插件有助于监控资源使用、时间、内存等。所有指标都存储在一个 sqlite 数据库中以供后期分析

退房 pytest 监视器 来自 pypi 或 conda-forge:

  • https://pypi.org/project/pytest-monitor/
  • https://github.com/CFMTech/pytest-monitor

  • 示例
    $ pytest --db ./monitor.db

    $ sqlite3 ./monitor.db

    sqlite>.headers on

    sqlite> select ITEM, MEM_USAGE from TEST_METRICS;

    ITEM|MEM_USAGE
    test_api/test_data_get[/data/listdsh]|17.5703125
    test_api/test_data_get[/data/listrecipients]|17.97265625
    test_api/test_data_get[/data/getuserdetails]|18.125


    希望这会有所帮助

    关于python - pytest:有没有办法报告测试的内存使用情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944777/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com