app性能自动化实践

"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨,请访问:https://ceshiren.com/t/topic/15860'
"""
import time

from utils.cmd_handle import cmd_handle
from utils.decorator_handle import thread_run
from utils.log_handle import CommonLog


class PerfHandle:
    """
    性能方法
    """
    log = CommonLog("PerfHandle").add_handle()
    device = None

    def get_cpu(self, package, device=None):
        """
        获取cpu数据
        :return:
        """
        c_cpu = 0
        cmd = "top -m 20 -n 1 -d 1"
        results = cmd_handle.cmd_adb_shell_start(cmd, device=self.device)
        for result in results:
            result = result.decode('UTF-8')
            if package in result:
                c_cpu = result.strip().split('%')[0].split(' ')[-1]
        self.log.info(f'get_cpu: {device},  c_cpu: {c_cpu}')
        return c_cpu

    def get_mem(self, package, device=None):
        """
        获取cpu数据
        :return:
        """
        c_mem = 0
        cmd = f"dumpsys meminfo {package}"
        results = cmd_handle.cmd_adb_shell_start(cmd, device=self.device)
        for result in results:
            result = result.decode('UTF-8')
            if "TOTAL" in result:
                c_mem = int(int(result.strip().split(' ')[3]) / 1024)
        self.log.info(f'get_mem: {device},  c_mem: {c_mem}')
        return c_mem

    def get_fps(self):
        """
        获取surface数据
        :return:
        """
        cmd = "service call SurfaceFlinger 1013"
        results = cmd_handle.cmd_adb_shell_start(cmd, device=self.device)
        c_fps = int(results[0].decode('UTF-8').split('(')[1].split(' ')[0], 16)
        self.log.info(f'get_fps: ,  c_fps: {c_fps}')
        return c_fps

    @thread_run
    def get_perf(self, package):
        """
        获取cpu,内存和帧率
        :param package:
        :return:
        """
        fps_a = self.get_fps()
        time_a = time.time()
        while True:
            time.sleep(1)
            fps_b = self.get_fps()
            time_b = time.time()
            cpu = self.get_cpu(package)
            mem = self.get_mem(package)
            fps = int((fps_b - fps_a) / int(time_b - time_a))
            fps_a = fps_b
            time_a = time_b
            self.log.info(f'cpu--{cpu}, mem--{mem}, fps--{fps}')

    def start_perf(self):
        self.get_perf('com.xueqiu.android')


perf_handle = PerfHandle()

if __name__ == '__main__':
    perf_handle.start_perf()
    print('开始用例执行,线程统计性能数据')
    time.sleep(10)
    print('结束')

关闭