代码改变世界

1、获取APP 冷/热启动时间

2018-07-30 16:36  软件测试汪  阅读(3540)  评论(0编辑  收藏  举报

最近在研究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