移动性能测试 python-monkey 压测 app 性能曲线图展示

测试小书童 · 2016年08月11日 · 最后由 测试小书童 回复于 2016年09月03日 · 2311 次阅读

简单介绍

  • pyhton+monkey 随机压测 app
  • python mat 生成曲线图

配置文件

## monkey.ini 配置文件
``` 配置
cmd=adb shell monkey -p com.dgm.user --throttle 500 --ignore-timeouts --ignore-crashes   --monitor-native-crashes -v -v
package_name=com.dgm.user
logdir=d:\android
remote_path=d:\android_server
phone_msg_log=d:\android_temp\phone.txt
sum = 100 -
activity = com.dgm.user.SplashActivity
exceptions=['NullPointer','IllegalState','IllegalArgument','ArrayIndexOutOfBounds','RuntimeException','SecurityException'] 

  • throttle 每次事件等待 500 毫秒
  • sum 定义随机事件数
  • exceptions 异常定义,用于后面扩展

代码分析

  • 获取 men cpu
import subprocess
pkg_name = "com.dgm.user"
cpu = []
men = []
def top_cpu(pkg_name):
    cmd = "adb shell dumpsys cpuinfo | grep " + pkg_name
    temp = []
    # cmd = "adb shell top -n %s -s cpu | grep %s$" %(str(times), pkg_name)
    top_info = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines()
    for info in top_info:
        temp.append(info.split()[2].decode()) # bytes转换为string
        # print("cpu占用:%s" %cpu)
    for i in temp:
         if i != "0%":
            cpu.append(i.split("%")[0])
    return cpu

def get_men(pkg_name):
    cmd = "adb shell  dumpsys  meminfo %s"  %(pkg_name)
    print(cmd)
    temp = []
    m = []
    men_s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines()
    for info in men_s:
        temp.append(info.split())
        # print("内存占用:%s" %men[19][1].decode()+"K")
    m.append(temp)
    for t in m:
        men.append(t[19][1].decode())
    return men
  • 入口代码
import monkeyConfig
from adb_common import AndroidDebugBridge as ai
import matplotlibBase as mt
import MenCpu as m
import datetime as dt
CPU = [[],[]] # time,使用情况
MEN = [[],[]] #当前时间,和内存使用情况
# 得到手机信息
def getPhoneMsg(cmd_log):
    l_list = []
    f = open(cmd_log, "r")
    lines = f.readlines()
    for line in lines:
        line = line.split('=')
        #Android 系统,如anroid 4.0
        if (line[0] == 'ro.build.version.release'):
            l_list.append(line[1])
            #手机名字
        if (line[0]=='ro.product.model'):
            l_list.append(line[1])
            #手机品牌
        if (line[0]=='ro.product.brand'):
            l_list.append(line[1])
    f.close()
    return l_list

#开始脚本测试
def start_monkey(cmd, logdir, now1, logcatname):
    print(cmd)
    os.popen(cmd)
    # os.kill()
    #使用Logcat导出日志"
    cmd2 = "adb logcat -d >%s" % logcatname
    os.popen(cmd2)
    #"导出traces文件"
    tracesname = logdir + "\\" + now1 + r"traces.log"
    cmd3 = "adb shell cat /data/anr/traces.txt>%s" % tracesname
    os.popen(cmd3)

if __name__ == '__main__':
    ini_file = 'monkey.ini'
    if os.path.isfile(ini_file):
        if ai().attached_devices():
            mc = monkeyConfig.baseReadnin(ini_file)
            ai().open_app(mc.get_package_name(), mc.get_activity())
            os.system('adb shell cat /system/build.prop >'+mc.get_phone_msg_log()) #存放的手机信息
            ll_list = getPhoneMsg(mc.get_phone_msg_log())
            # monkey开始测试
            sum = mc.get_sum()
            temp = ""
            monkeylog = ""
            start_monkey(mc.get_cmd(), mc.get_logdir(), mc.get_now(), mc.get_logcatname())
            for i in range(sum):
                time.sleep(1)
                print(i)
                dn = dt.datetime.now()
                CPU[0].append(dn)
                m.top_cpu(mc.get_package_name())
                MEN[0].append(dn)
                m.get_men(mc.get_package_name())
                monkeylog = open(mc.get_logdir() + "\\" + mc.get_now()+"monkey.log")
                temp = monkeylog.read()
                monkeylog.close()
                if temp.count('Monkey finished')>0:
                    print("测试完成咯")
                    CPU[1].append(m.cpu)
                    MEN[1].append(m.men)
                    # geterror(ll_list, mc.get_log(), mc.get_remote_path(), mc.now) 错误显示
                    mt.cpu_men_plots(CPU, MEN)
                    break
        else:
            print("设备不存在")
    else:
        print(u"配置文件不存在"+ini_file)
  • 结果以曲线图展示
def cpu_men_plots(cpu, men):
    import matplotlib.pyplot as pl
    import matplotlib.dates as mdates
    import datetime

    # 处理异常数据,有时候得到数据(占用情况)会比时间多一次循环的数据,造成xy的数据不一致,而引起报错
    if len(cpu[0]) != len(cpu[1][0]):
        cpu[1][0]= cpu[1][0][0:len(cpu[0])]

    if len(men[0]) != len(men[1][0]):
        men[1][0]= men[1][0][0:len(men[0])]
    print(men[0])
    print(men[1][0])
    a1 = pl.subplot(311)
    a1.set_title("CPU")
    a1.set_ylabel("占用情况%")
    a1.plot(cpu[0], cpu[1][0])
    a1.xaxis.set_major_locator(mdates.SecondLocator(interval=1))
    a1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))

    a2 = pl.subplot(312)
    a2.set_title("内存")
    a2.set_ylabel("使用情况 K")
    a2.plot(men[0], men[1][0])
    a2.xaxis.set_major_locator(mdates.SecondLocator(interval=2))
    a2.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))

    # a3 = pl.subplot(313)
    # a3.set_title("流量")
    # a3.set_ylabel("使用情况 K")
    # a3.plot(x,list2)
    # a3.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))

    # a1.margins(x=0.2)
    pl.tight_layout()
    pl.show()

结束语

  • 很多资料都是在论坛里面学习的,基本上大部分思路来自于论坛的性能测试合集,但是我看没有出一个完整的解决方案,自己就整理了一个
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 12 条回复 时间 点赞

不错学习了

能说明说明问题 结果? 如果执行的项目本来就耗 CPU 呢

其实不建议用 adb 获取 对性能有影响 但是 py 下好像也没有很好的办法 🗿

monkeyConfig AndroidDebugBridge matplotlibBase 这几个是 lz 自己写的么

服务器方面的性能测试 LR、nmon 可以生成详细的报告,app 这块的测试只能用 python 或其方式实现图形化的展现么?

#5 楼 @robin1008 方式有很多,不要被工具遮住了眼睛。就像我之前用的是 js+html 展示服务器的性能指标

#6 楼 @lose 感觉是有一点,一上来就找工具,想把结果展示的很好,其实把几个核心的命令掌握好,一样能分析出问题。。

phton mat 是什么鬼,写错了吧

楼主,请教下怎么实时的展示曲线图?

—— 来自 TesterHome 官方 安卓客户端

#8 楼 @mads 看代码啊 人家简写了

#10 楼 @kevin_sqa 😂 明明是写错了好么

#11 楼 @mads 😇 哈哈~ 你够屌

测试小书童 [该话题已被删除] 中提及了此贴 09月03日 11:26
测试小书童 关闭了讨论 09月03日 11:28
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册