yappi,Python性能分析库

yappi是为Python设计的线程感知型性能分析器,不仅支持CPU时间分析,还能够准确追踪线程级别的性能问题。

安装

pip install yappi -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

基本用法

import yappi
import time
import threading


def func1():
    time.sleep(2)


def func2():
    time.sleep(2)


# 启动性能分析
yappi.start()

# 创建并运行多个线程
t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)
t1.start()
t2.start()
t1.join()
t2.join()

# 获取并打印统计结果
stats = yappi.get_func_stats()
stats.print_all()

# 停止分析
yappi.stop()

字段解释

  • ncalls: 函数被调用的次数。
  • tsub: 函数自身消耗的时间(不包括子函数)。
  • ttot: 函数总消耗的时间(包括子函数)。
  • tavg: 平均每次调用消耗的时间。
  • name: 函数名称。

 

高级用法

import yappi
import time

# 设置时钟类型
yappi.set_clock_type("cpu")  # 或 "wall"


# 自定义上下文管理器
class YappiProfile:

    def __enter__(self):
        yappi.start()
        return self

    def __exit__(self, *args):
        yappi.stop()
        stats = yappi.get_func_stats()
        stats.save('profile.prof', 'pstat')
        yappi.clear_stats()


def func1():
    time.sleep(2)


def func2():
    time.sleep(2)


with YappiProfile():
    func1()
    func2()

运行完成后会生成一个 profile.prof 文件

import pstats

# 读取 profile.prof 文件
p = pstats.Stats('profile.prof')

# 打印出所有函数的性能统计信息
p.sort_stats('cumulative').print_stats()

 

 

posted @ 2025-01-17 15:29  北京测试菜鸟  阅读(190)  评论(0)    收藏  举报