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