Python获取android设备cpu和内存占用情况_python

来源:脚本之家  责任编辑:小易  

#!/usr/bin/env python # -*- coding: utf-8 -*- import wmiimport timedef cpu_mem(): c = wmi.WMI() for processor in c.Win32_Processor(): print ("Processor ID: %s" % processor.DeviceID ) print( "Process Name: %s" % processor.Name.strip() ) for Memory in c.Win32_PhysicalMemory(): print( "Memory Capacity: %.fMB" %(int(Memory.Capacity)/1048576) )def cpu_use(): c = wmi.WMI() for i in range(1,3): # while True for cpu in c.Win32_Processor(): timestamp = time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime()) print( ' %s |e69da5e6ba9062616964757a686964616f31333361323031 Utilization: %s: %d %%' % (timestamp, cpu.DeviceID, cpu.LoadPercentage)) time.sleep(3)def main(): cpu_mem() cpu_use()本回答被提问者采纳www.zgxue.com防采集请勿采集本网。

功能:获取android设备中某一个app的cpu和内存

1. 使用装饰器来衡量函数执行时间 有一个简单方法,那就是定义一个装饰器来测量函数的执行时间,并输出结果: import time from functools import wraps def fn_timer(function): @wraps(function) def function_timer(*args, **kwargs): t0 = t

环境:python和adb

如果想自己写程序来实现的话,可以参考它们的源码。 top/free都是在procps包中(apt-get source procps)。 找到cpus_refresh()函数,你可以看到它是怎样从/proc/stat解析出CPU的使用率的。meminfo()函数则展示了如何从/proc/meminfo解析出内存的

使用方法:使用adb连接android设备,打开将要测试的app,执行cpu/内存代码

用过,没当真,其实这些软件都在做脱裤子放屁的事,没什么实际意义

cpu获取代码如下:(输入参数为脚本执行时间)

Ubuntu10.10 下解决Python CPU占用100%的方法 收藏 在Ubuntu10.10中,python-ibus中存在问题,这个是10.10中的python有bug。 是由于使用输入法过程中点击了设置属性页所引起的,注销一下再登录桌面就好了。 彻底的解决办法是添加更新此源:ppa:k

# coding:utf-8'''获取系统total cpu'''import os, csvimport timeimport csvimport numpy as npfrom matplotlib import pyplot as pltcpu_list = []time_list = []app_list = []lines = []package_name = []# 读取进程名称(包名)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数值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: # 适配低版本手机 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 # 适配高版本手机 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()# 将数值写入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]}") # 根据数据绘制图形 plt.figure(figsize=(11, 4), dpi=600) # 生成网格 # 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]) # 坐标轴范围 # 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() # 横坐标显示间隔 if len(wights) <= 15: pass else: t = int(len(wights) / 15) plt.xticks(range(0, len(wights), t)) # 纵坐标显示间隔 # plt.yticks(range(100, 300, 10)) # 旋转日期 plt.gcf().autofmt_xdate() # 展示每个坐标 # 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"将要监测的包名为:{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(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("请输入脚本执行时间(分钟):")) start_time = time.time() get_applist() write_head() time_control() write_report() mapping()

这个需要进进程管理查看 如何打开进程管理器 快捷键Ctrl+Alt+方向键下键(或者小键盘的Enter键)

会在.py文件同级目录下生成3个文件夹,config、log_su、report,其中运行结果在report中

结果以是生成折线图,看起来直观,如下:

这里我解释下,cpu占比是adb获取的实时占比,但是满值并不一定是100%,比如这张图,用的是一个八核的手机,所以CPU满值是800%

内存获取代码如下:(输入参数为脚本执行时间)

# coding:utf-8'''获取系统total memory'''import os, csvimport timeimport csvimport numpy as npfrom matplotlib import pyplot as pltmem_dict = {}time_list = []app_list = []package_name = []t = 0def 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) breakdef 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"内存值:{highs_float}") # 输出平均值 total = 0 for value in highs_float: total += value average = round(total / len(highs_float), 2) print(f"内存平均值:{average}") # 输出最低值和最高值 highs_hl = sorted(highs_float) print(f"内存最低值:{highs_hl[0]}") print(f"内存最高值:{highs_hl[len(highs_hl) - 1]}") # 根据数据绘制图形 plt.figure(figsize=(11, 4), dpi=600) # 生成网格 # 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]) # 坐标轴范围 # 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() # 横坐标显示间隔 if len(wights) <= 15: pass else: t = int(len(wights) / 15) plt.xticks(range(0, len(wights), t)) # 坐标刻度 # 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)) #旋转日期 plt.gcf().autofmt_xdate() # 展示每个坐标 # 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"将要监测的包名为:{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("请输入脚本执行时间(分钟):")) start_time = time.time() get_applist() write_head() time_control() mapping()

会在.py文件同级目录下生成3个文件夹,config、log_su、report,其中运行结果在report中

生成的内存结果图如下:

到此这篇关于Python获取android设备cpu和内存占用情况的文章就介绍到这了,更多相关Python获取android设备内容请搜索真格学网以前的文章或继续浏览下面的相关文章希望大家以后多多支持真格学网! 您可能感兴趣的文章:通过Python 获取Android设备信息的轻量级框架python获取android设备的GPS信息脚本分享

看到句柄数这几个字,我猜可能是要windows下运行的?可能答非所问,不过在linux下最好的用的莫636f707962616964757a686964616f31333337626266过于psutil了,你可以通过进程名或pid很好的监控任意进程的系统占用情况,甚至进程建立的每个连接都能获取到>>> import psutil>>> psutil.pids()[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215, 1216, 1220, 1221, 1243, 1244, 让渣1301, 1601, 2237, 2355, 2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358, 4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235, 5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]>>>>>> p = psutil.Process(7055)>>> p.name()'python'>>> p.exe()'/usr/bin/python'>>> p.cwd()'/home/giampaolo'>>> p.cmdline()['/usr/bin/python', 'main.py']>>>>>> p.status()'running'>>> p.cpu_percent(interval=1.0)12.1>>>坦橡悄 psutil.net_io_counters(pernic=True){'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0), 'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)}从官方文档上copy了一部分出来,有没有碉堡了的感觉,快去翻一如敬下文档吧,非常容易使用,  你可以使用baiWMI,比你du从任务管理器中看到的zhi指标还要多,dao所以,你需内要从中提取你所关心的内容容。  英特尔最新推出了第六代酷睿产品,采用全新一代的架构,性能提示、功能降低、续航更加长久、无论办公学习、畅玩游戏或者观看超高清音箱播放,均得心应手,您也可以试试内容来自www.zgxue.com请勿采集。


  • 本文相关:
  • 在python中,使用scatter绘制散点图的实例
  • pycharm软件实现设置自动保存操作
  • python面向对象之类和对象属性的增删改查操作示例
  • python实现读取邮箱中的邮件功能示例【含文本及附件】
  • python svd压缩图像的实现代码
  • 使用pycharm安装pytest及requests的问题
  • 基于python-pptx库中文文档及使用详解
  • python多进程原理与用法分析
  • pyqt5每天必学之日历控件qcalendarwidget
  • python编程实现12306的一个小爬虫实例
  • 怎么用python查询出 进程 CPU使用率 内存使用 句柄数
  • 如何用Python实现cpu和内存的监控
  • Python 怎样获取当前计算机的 cpu,内存等信息
  • 求一个python模块,用于获取一组主机的cpu、内存、...
  • 如何查看python脚本运行时cup和内存的消耗
  • python怎样获得当前系统的CPU频率和内存使用情况
  • 有谁用python监视过windows下指定进程的CPU占有率...
  • ubuntu 下,python 占用cpu资源超大,经常100%
  • python怎么获取自身进程的CPU和内存使用情况
  • python脚本怎么在linux上获取cpu的使用率
  • 网站首页网页制作脚本下载服务器操作系统网站运营平面设计媒体动画电脑基础硬件教程网络安全vbsdos/bathtahtcpythonperl游戏相关vba远程脚本coldfusionruby专题autoitseraphzonepowershelllinux shellluagolangerlang其它首页通过python 获取android设备信息的轻量级框架python获取android设备的gps信息脚本分享在python中,使用scatter绘制散点图的实例pycharm软件实现设置自动保存操作python面向对象之类和对象属性的增删改查操作示例python实现读取邮箱中的邮件功能示例【含文本及附件】python svd压缩图像的实现代码使用pycharm安装pytest及requests的问题基于python-pptx库中文文档及使用详解python多进程原理与用法分析pyqt5每天必学之日历控件qcalendarwidgetpython编程实现12306的一个小爬虫实例python入门教程 超详细1小时学会pycharm 2020最新永久激活码(附python 列表(list)操作方法详解python 元组(tuple)操作详解python 字典(dictionary)操作详解pycharm 使用心得(一)安装和首python strip()函数 介绍python 中文乱码问题深入分析python中使用xlrd、xlwt操作excepycharm 2020年最新激活码(亲测python使用mongodb保存爬取豆瓣电影的数据python导包的几种方法(自定义包的生成以及win与linux系统中python requests 安装python3实现的爬虫爬取数据并存入mysql数python3的urllib.parse常用函数小结(urlepython实现朴素贝叶斯的学习与分类过程解python list列表中删除多个重复元素操作示python之消除前缀重命名的方法python 安装 virturalenv 虚拟环境的教程网易2016研发工程师编程题 奖学金(pytho
    免责声明 - 关于我们 - 联系我们 - 广告联系 - 友情链接 - 帮助中心 - 频道导航
    Copyright © 2017 www.zgxue.com All Rights Reserved