Python獲取android設(shè)備cpu和內(nèi)存占用情況
功能:獲取android設(shè)備中某一個app的cpu和內(nèi)存
環(huán)境:python和adb
使用方法:使用adb連接android設(shè)備,打開將要測試的app,執(zhí)行cpu/內(nèi)存代碼
cpu獲取代碼如下:(輸入?yún)?shù)為腳本執(zhí)行時間)
# coding:utf-8 ''' 獲取系統(tǒng)total cpu ''' import os, csv import time import csv import numpy as np from matplotlib import pyplot as plt cpu_list = [] time_list = [] app_list = [] lines = [] package_name = [] # 讀取進(jìn)程名稱(包名) def get_applist(): global package_name with open('config/director.txt', encoding='utf-8', mode='r') as f: lines_all = f.readlines() for appname in lines_all: package_name1 = appname appname_new = appname[0:15] package_name.append(package_name1) lines.append(appname_new) for line in lines: app_list.append(line.strip()) # 獲取cpu數(shù)值 def get_cpu(): global filename with open(filename, encoding="utf-8", mode="r") as f: lines = f.readlines() for appname in app_list: for lis in lines: # 適配低版本手機(jī) if appname in lis and '%' in lis: now = time.strftime("%H:%M:%S", time.localtime()) time_list.append(now) cpu_1 = lis.split('%')[0] cpu_2 = cpu_1.split(' ') # print(cpu_2) cpu = cpu_2[len(cpu_2) - 1] print(cpu, now) cpu_list.append(cpu) break # 適配高版本手機(jī) elif appname in lis: now = time.strftime("%H:%M:%S", time.localtime()) time_list.append(now) cpu1 = lis.split(' ') # print(cpu1) cpu2 = list(set(cpu1)) cpu2.sort(key=cpu1.index) cpu_h = cpu2[len(cpu2) - 4] print(cpu_h, now) cpu_list.append(cpu_h) break else: pass # csv頭部 def write_head(): headers = ['name:'] headers.append(app_list[0]) headers.append('init_cpu') with open('log_su/cpuinfo.csv', 'w+', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() # 將數(shù)值寫入csv,用于繪圖時讀取 def write_report(): # headers = ['name', 'aaa', 'init_cpu'] with open('log_su/cpuinfo.csv', 'a+', newline='') as csvfile: writer = csv.writer(csvfile) for key in cpu_list: writer.writerow([' ', ' ', key]) # 繪制折線圖,生成測試報告 def mapping(): filename = 'log_su/cpuinfo.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) highs = [] for row in reader: high = row[2] highs.append(high) # print(highs) wights = time_list highs_float = list(map(float, highs)) # print(f"****{highs}") print(f"CPU值:{highs_float}") # 輸出平均值 total = 0 for value in highs_float: total += value average = round(total/len(highs_float), 2) print(f"CPU平均值:{average}") #輸出最低值和最高值 highs_hl = sorted(highs_float) print(f"CPU最低值:{highs_hl[0]}") print(f"CPU最高值:{highs_hl[len(highs_hl)-1]}") # 根據(jù)數(shù)據(jù)繪制圖形 plt.figure(figsize=(11, 4), dpi=600) # 生成網(wǎng)格 # plt.grid() plt.grid(axis="y") # 折線圖 if package_name[0] == 'com.oneapp.max.security.pro.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="PPP") elif package_name[0] == 'com.oneapp.max.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="Opt1.6.1") elif package_name[0] == 'com.boost.clean.coin.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="Fastclear") elif package_name[0] == 'com.walk.sports.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="Walk") elif package_name[0] == 'com.diamond.coin.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="Amber") elif package_name[0] == 'com.oneapp.max.cleaner.booster.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="Space") else: plt.plot(wights, highs_float, "c-", linewidth=1, label=package_name[0]) # 坐標(biāo)軸范圍 # plt.ylim(300, 400) # plt.xlim(0, 10) plt.xlabel('time(H:Min:S)', fontsize=16) plt.ylabel("cpu_realtime(%)", fontsize=16) plt.title("cpu real time line chart", fontsize=24) plt.legend() # 橫坐標(biāo)顯示間隔 if len(wights) <= 15: pass else: t = int(len(wights) / 15) plt.xticks(range(0, len(wights), t)) # 縱坐標(biāo)顯示間隔 # plt.yticks(range(100, 300, 10)) # 旋轉(zhuǎn)日期 plt.gcf().autofmt_xdate() # 展示每個坐標(biāo) # for a, b in zip(wights, highs_float): # plt.text(a, b, (a, b), ha='center', va='bottom', fontsize=8) # plt.show() time_now = time.strftime("%m%d-%H:%M:%S", time.localtime()) path = "report/" + time_now plt.savefig(path) # 自動識別當(dāng)前需檢測的 def name_app(): cmd = 'adb shell dumpsys window | grep mCurrentFocus > log_su/name_info.csv' os.system(cmd) with open('log_su/name_info.csv', encoding='utf-8', mode='r') as f: lines = f.readlines() for line in lines: if 'mCurrentFocus' in line: name1 = line.split('/')[0].split(' ') name = name1[len(name1) - 1] with open('config/director.txt', encoding='utf-8', mode='w') as f_name: text = name f_name.write(text) print(f"將要監(jiān)測的包名為:{text}") #控制監(jiān)測時間 def time_control(): global filename while True: end_time = time.time() if (end_time - start_time)/60 >= tol_time: #分鐘 # if end_time - start_time >= tol_time: # 秒 break time.sleep(1) adb = "adb shell top -n 1 > log_su/adb_info.csv" d = os.system(adb) filename = "log_su/adb_info.csv" get_cpu() if __name__ == "__main__": name_app() tol_time = int(input("請輸入腳本執(zhí)行時間(分鐘):")) start_time = time.time() get_applist() write_head() time_control() write_report() mapping()
會在.py文件同級目錄下生成3個文件夾,config、log_su、report,其中運行結(jié)果在report中
結(jié)果以是生成折線圖,看起來直觀,如下:
這里我解釋下,cpu占比是adb獲取的實時占比,但是滿值并不一定是100%,比如這張圖,用的是一個八核的手機(jī),所以CPU滿值是800%
內(nèi)存獲取代碼如下:(輸入?yún)?shù)為腳本執(zhí)行時間)
# coding:utf-8 ''' 獲取系統(tǒng)total memory ''' import os, csv import time import csv import numpy as np from matplotlib import pyplot as plt mem_dict = {} time_list = [] app_list = [] package_name = [] t = 0 def get_applist(): global package_name with open('config/director.txt', encoding='utf-8', mode='r') as f: lines = f.readlines() for line in lines: package_name1 = line package_name.append(package_name1) app_list.append(line.strip()) def get_mem(): global filename with open(filename, encoding="utf-8", mode="r") as f: lines = f.readlines() start_flag = False for appname in app_list: for line in lines: if "Total PSS by OOM adjustment" in line: break if appname in line and 'pid' in line and 'kB' in line: mem_v = line.strip().split(':')[0].replace('kB', '').replace(',', '') line_name = line.split(':')[1].split('(')[0].strip() if line_name in appname: mem_v = round(float(mem_v) / 1024, 2) mem_dict[appname] = mem_v now_v = time.strftime("%H:%M:%S", time.localtime()) # now_int = int(now_v) time_list.append(now_v) print(mem_v, now_v) break elif appname in line and 'pid' in line and 'K' in line: mem_v = line.strip().split(':')[0].replace('K', '').replace(',', '') line_name = line.split(':')[1].split('(')[0].strip() if line_name in appname: mem_v = round(float(mem_v) / 1024, 2) mem_dict[appname] = mem_v now_v = time.strftime("%H:%M:%S", time.localtime()) # now_int = int(now_v) time_list.append(now_v) print(mem_v, now_v) break def write_head(): headers = ['name:'] headers.append(app_list[0]) headers.append('init_mem') with open('log_su/meminfo.csv', 'w+', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() def write_report(): headers = ['name','aaa', 'init_mem'] with open('log_su/meminfo.csv', 'a+', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers) for key in mem_dict: writer.writerow({'init_mem': mem_dict[key]}) def mapping(): filename = 'log_su/meminfo.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) highs = [] for row in reader: high = row[2] highs.append(high) # print(highs) wights = time_list highs_float = list(map(float, highs)) print(f"內(nèi)存值:{highs_float}") # 輸出平均值 total = 0 for value in highs_float: total += value average = round(total / len(highs_float), 2) print(f"內(nèi)存平均值:{average}") # 輸出最低值和最高值 highs_hl = sorted(highs_float) print(f"內(nèi)存最低值:{highs_hl[0]}") print(f"內(nèi)存最高值:{highs_hl[len(highs_hl) - 1]}") # 根據(jù)數(shù)據(jù)繪制圖形 plt.figure(figsize=(11, 4), dpi=600) # 生成網(wǎng)格 # plt.grid() plt.grid(axis="y") if package_name[0] == 'com.oneapp.max.security.pro.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="PPP") elif package_name[0] == 'com.oneapp.max.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="Opt") elif package_name[0] == 'com.boost.clean.coin.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="fastclear") elif package_name[0] == 'com.walk.sports.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="Walk") elif package_name[0] == 'com.diamond.coin.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="Amber") elif package_name[0] == 'com.oneapp.max.cleaner.booster.cn': plt.plot(wights, highs_float, "c-", linewidth=1, label="Space") else: plt.plot(wights, highs_float, "c-", linewidth=1, label=package_name[0]) # 坐標(biāo)軸范圍 # plt.ylim(300, 400) # plt.xlim(0, 10) plt.xlabel('time(H:Min:S)', fontsize=16) plt.ylabel("Number (Mb)", fontsize=16) plt.title("meminfo", fontsize=24) plt.legend() # 橫坐標(biāo)顯示間隔 if len(wights) <= 15: pass else: t = int(len(wights) / 15) plt.xticks(range(0, len(wights), t)) # 坐標(biāo)刻度 # my_y_ticks = np.arange(300, 400, 10) # my_x_ticks = np.arange(1, 10, 1) # plt.xticks(my_x_ticks) # plt.yticks(my_y_ticks) # plt.yticks(range(100, 300, 10)) #旋轉(zhuǎn)日期 plt.gcf().autofmt_xdate() # 展示每個坐標(biāo) # for a, b in zip(wights, highs_float): # plt.text(a, b, (a, b), ha='center', va='bottom', fontsize=8) # plt.show() time_now = time.strftime("%m%d-%H:%M:%S", time.localtime()) path = "report/" + time_now plt.savefig(path) def name_app(): cmd = 'adb shell dumpsys window | grep mCurrentFocus > log_su/name_info.csv' os.system(cmd) with open('log_su/name_info.csv', encoding='utf-8', mode='r') as f: lines = f.readlines() for line in lines: if 'mCurrentFocus' in line: name1 = line.split('/')[0].split(' ') name = name1[len(name1) - 1] with open('config/director.txt', encoding='utf-8', mode='w') as f_name: text = name f_name.write(text) print(f"將要監(jiān)測的包名為:{text}") def time_control(): global filename while True: end_time = time.time() if (end_time - start_time)/60 >= tol_time: #分鐘 # if end_time - start_time >= tol_time: #秒 break # time.sleep(2) # filename = str(input("請輸入文件名:")) adb = "adb shell dumpsys meminfo > log_su/adb_info.csv" d = os.system(adb) filename = "log_su/adb_info.csv" get_mem() write_report() if __name__ == "__main__": name_app() tol_time = int(input("請輸入腳本執(zhí)行時間(分鐘):")) start_time = time.time() get_applist() write_head() time_control() mapping()
會在.py文件同級目錄下生成3個文件夾,config、log_su、report,其中運行結(jié)果在report中
生成的內(nèi)存結(jié)果圖如下:
到此這篇關(guān)于Python獲取android設(shè)備cpu和內(nèi)存占用情況的文章就介紹到這了,更多相關(guān)Python獲取android設(shè)備內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 解決Android 高CPU占用率的問題
- Android、Flutter為不同的CPU架構(gòu)包打包APK(v7a、v8a、x86區(qū)別)
- 淺析AndroidStudio3.0最新 Android Profiler分析器(cpu memory network 分析器)
- Android編程實現(xiàn)獲取系統(tǒng)內(nèi)存、CPU使用率及狀態(tài)欄高度的方法示例
- Android獲取設(shè)備CPU核數(shù)、時鐘頻率以及內(nèi)存大小的方法
- 解析Android獲取系統(tǒng)cpu信息,內(nèi)存,版本,電量等信息的方法詳解
- android獲取手機(jī)cpu并判斷是單核還是多核
- Android 輕松獲取CPU型號的方法
相關(guān)文章
python用pd.read_csv()方法來讀取csv文件的實現(xiàn)
本文主要介紹了python用pd.read_csv()方法來讀取csv文件的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06Python 讀取有公式cell的結(jié)果內(nèi)容實例方法
在本篇文章里小編給大家整理的是關(guān)于Python 如何讀取有公式cell的結(jié)果內(nèi)容,需要的朋友們可以學(xué)習(xí)下。2020-02-02