android 冷热启动时候收集

◇◆丶佛笑我妖孽 提交于 2019-12-15 01:42:11

Android启动时间----获取APP 冷/热启动时间
转载java2013liu 发布于2019-05-30 17:15:20 阅读数 430 收藏
展开
最近在研究Android APP性能测试。所以发现一些有趣的东西,在这里进行分享。我们先讲第一个内容,如何获取APP冷/热启动时间?为什么要做这个测试,道理其实很简单,如果启动APP特别耗时的话,用户反馈百分之99不好。所以在这里我们可以获取APP冷/热启动时间,同竞品进行比较。

环境准备(可参考我写的monkey测试)
adb
手机/模拟器
cmder
python2

获取APK包名及主活动名
adb logcat | grep START //监控指令

具体步骤:
1、cmder下输入 adb logcat | grep START

2、点击想监控的APP,比如这里我点击的是手机自带浏览器,然后会生成一些log,我们找到cmp,如下 com.android.browser 是我们要找的包名,.BrowserActivity 是我们找的主活动名

Windows下获取APP 冷/热启动时间
冷启动
adb shell am start -W -n com.android.browser/.BrowserActivity

冷启动停止APP
adb shell am force-stop com.android.browser

热启动
adb shell am start -W -n com.android.browser/.BrowserActivity

热启动停止APP
adb shell input keyevent 3

python脚本实现APP 冷/热启动时间
思路:

  1. 创建一个APP类,进行APP相关操作,其中包含,冷/热启动APP,冷/热关闭APP,获取冷/热启动时间

  2. 创建一个Controller类,主要实现多次启动/关闭APP,获取时间戳,数据的存储

复制代码

/usr/bin/python

encoding:utf-8

import csv
import os
import time

class App(object):
def init(self):
self.content = “”
self.startTime = 0

# 启动App
def LaunchApp(self):
    cmd = 'adb shell am start -W -n com.begoit.studyplan/.ui.act.SplashActivity'
    self.content = os.popen(cmd)

# 停止App
def StopApp(self):
    # cmd = 'adb shell am force-stop com.android.browser'
    cmd = 'adb shell input keyevent 3'
    os.popen(cmd)

# 获取启动时间
def GetLaunchedTime(self):
    for line in self.content.readlines():
        if "ThisTime" in line:
            self.startTime = line.split(":")[1]
            break
    return self.startTime

控制类

class Controller(object):
def init(self, count):
self.app = App()
self.counter = count
self.alldata = [(“timestamp”, “elapsedtime”)]

# 单次测试过程
def testprocess(self):
    self.app.LaunchApp()
    time.sleep(5)
    elpasedtime = self.app.GetLaunchedTime()
    self.app.StopApp()
    time.sleep(3)
    currenttime = self.getCurrentTime()
    self.alldata.append((currenttime, elpasedtime))

# 多次执行测试过程
def run(self):
    while self.counter > 0:
        self.testprocess()
        self.counter = self.counter - 1

# 获取当前的时间戳
def getCurrentTime(self):
    currentTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    return currentTime

# 数据的存储
def SaveDataToCSV(self):
    csvfile = file('startTime2.csv', 'wb')
    writer = csv.writer(csvfile)
    writer.writerows(self.alldata)
    csvfile.close()

if name == “main”:
controller = Controller(5)
controller.run()
controller.SaveDataToCSV()
复制代码

运行结果展示:

总结:

我们通过两种方式实现记录APP冷/热启动时间,进行比较,编写脚本方式相对简单些。也更容易对测试结果进行分析。所以在这里推荐大家学习python基础知识。关于adb shell am 的命令推荐阅读:https://blog.csdn.net/soslinken/article/details/50245865

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!