客户端性能-iOS端性能采集tidevice基本用法示例

# python3
# coding=utf-8
#######################################################################
"""
 File Name: ios_perf_demo.py
 Description: iOS性能测试demo, 使用tidevice库实现
 Author: alisleepy
"""
#######################################################################


"""
使用说明:
    0、前置条件:
        手机上需要安装WDA工具,需要将手机添加到开发者证书号列表中
    1、安装依赖:
        pip install tidevice
    2、获取设备ID:
        idevice_id
    3、执行,获取输出结果:
        python ios_perf_demo.py
    4、tidevice默认没有rss_value,需要手动修改源码添加:
        修改路径:/usr/local/lib/python3.8/dist-packages/tidevice/_perf.py
        添加代码如下:只增加rss_value即可
        yield DataType.MEMORY, {
            "pid": minfo['pid'],
            "timestamp": gen_stimestamp(),
            "value": minfo['phys_memory'] / 1024 / 1024,  # MB
            "rss_value": minfo['rss'] / 1024 / 1024
        }
"""


import time
import traceback
import tidevice
from tidevice._perf import DataType


class iOSPerfDemo():
    """
    iOS性能测试类
    """

    def __init__(self, udid, package_name, collect_time):
        """
        初始化
        Args:
        udid(str): 设备ID
        package_name(str): 包名
        collect_time(int): 采集时长
        """
        self.udid = udid
        self.package_name = package_name
        self.collect_time = collect_time
        if not self.udid or len(self.udid) == 0:
            raise Exception('请输入正确的设备ID')
        if not self.package_name or len(self.package_name) == 0:
            raise Exception('请输入正确的包名')
        if not self.collect_time or not isinstance(self.collect_time, int):
            raise Exception('请输入正确的采集时间')

    def start_perf(self):
        """
        启动性能测试
        """
        # 从tidevice获取的原始数据
        ori_cpu_list = []
        ori_physical_memory_list = []
        # rss_memory_list = []
        # rss_memory_detail = ""
        # ori_network_list = []
        # ori_gpu_list = []
        # ori_fps_list = []

        # 处理之后的数据
        new_cpu_list = []
        cpu_detail = ""
        new_physical_memory_list = []
        physical_memory_detail = ""
        # new_rss_memory_list = []
        # new_rss_memory_detail = ""

        try:
            t = tidevice.Device(udid=self.udid)
            perf = tidevice.Performance(
                t,
                # 要采集的数据类型
                [
                    DataType.CPU,         # CPU使用率
                    DataType.MEMORY,      # 内存使用
                    # DataType.NETWORK,     # 流量
                    # DataType.FPS,         # 帧率
                    # DataType.PAGE,        # 页面切换
                    # DataType.SCREENSHOT,  # 截屏
                    # DataType.GPU          # GPU使用率
                ]
            )

            def callback(_type: tidevice.DataType, value: dict):
                """
                回调函数
                Args:
                    _type(tidevice.DataType): 数据类型
                    value(dict): 数据值
                """
                try:
                    if _type == tidevice.DataType.CPU:
                        # print("cpu_value:", value)
                        ori_cpu_list.append(value)
                    if _type == tidevice.DataType.MEMORY:
                        # print("memory_value:", value)
                        ori_physical_memory_list.append(value)
                    # if _type == tidevice.DataType.NETWORK:
                    #     ori_network_list.append(value)
                    # if _type == tidevice.DataType.GPU:
                    #     ori_gpu_list.append(value)
                    # if _type == tidevice.DataType.FPS:
                    #     ori_fps_list.append(value)
                    # if _type == tidevice.DataType.GPU:
                    #     ori_gpu_list.append(value)
                except Exception as e:
                    print("error -> ", str(e))
                    print(traceback.format_exc())

            # 启动性能测试
            perf.start(self.package_name, callback=callback)
            time.sleep(self.collect_time)
            perf.stop()

            # 采集结束,循环处理获取cpu
            for item in ori_cpu_list:
                try:
                    cpu = float('{:0.3f}'.format(item["value"]))
                except Exception as e:
                    print("异常cpu->", cpu)
                    continue
                # 丢弃cpu为0的情况
                if int(cpu) == 0:
                    continue
                if cpu >= 0.001:
                    mtime = round(item["timestamp"] / 1000)
                    ltime = time.localtime(mtime)
                    timestr = time.strftime("%Y-%m-%d %H:%M:%S", ltime)
                    cpu_detail = cpu_detail + str(cpu) + "," + str(timestr) + ";"
                    new_cpu_list.append(cpu)

            # 循环处理获取内存
            for item in ori_physical_memory_list:
                mem = float('{:0.3f}'.format(item["value"]))
                # rss_mem = float('{:0.3f}'.format(item["rss_value"]))
                # 丢弃mem为0的情况
                if int(mem) == 0:  # or int(rss_mem) == 0:
                    continue
                if mem >= 0.001:  # and rss_mem >= 0.001:
                    mtime = round(item["timestamp"] / 1000)
                    ltime = time.localtime(mtime)
                    timestr = time.strftime("%Y-%m-%d %H:%M:%S", ltime)
                    # 物理内存
                    physical_memory_detail = physical_memory_detail + str(mem) + "," + str(timestr) + ";"
                    new_physical_memory_list.append(float(mem))
                    # 暂时不处理rss_memory
                    # rss_memory_detail = rss_memory_detail + str(rss_mem) + "," + str(timestr) + ";"
                    # new_rss_memory_list.append(float(rss_mem))

            # 打印结果
            print("------------------\n以下分别为CPU和内存使用情况----------------")
            print(new_cpu_list)
            print(new_physical_memory_list)
        except Exception as e:
            print("error -> ", str(e))
            print(traceback.format_exc())


if __name__ == '__main__':
    """
    主函数
    """
    # 设备ID
    udid = "07dd23aa7a9193c54-XXXX"
    package_name = "com.baidu.map"
    collect_time = 10
    ios_perf_demo = iOSPerfDemo(udid, package_name, collect_time)
    ios_perf_demo.start_perf()

posted @ 2025-04-08 11:33  alisleepy  阅读(90)  评论(0)    收藏  举报