当前位置 博文首页 > 华~的博客:使用python统计Android应用内存以及CPU占用
class Cmd:
CMD_PS = 'adb shell "ps |grep 包名"'
CMD_TOP = 'adb shell "top -p %s -n 1"'
CMD_TOP_8937 = 'adb shell "top -m 1 -n 1"'
CMD_PROCRANK = 'adb shell "procrank |grep 包名"'
class AdbUtil(object):
USER_CPU_TEST_COUNT = 10
USER_MEMORY_TEST_COUNT = 5
USER_DEVICE_PHONE = "PHONE"
USER_DEVICE_8937 = "8937"
USER_DEVICE_TYPE = USER_DEVICE_8937
"""
:解析应用PID
"""
def _find_pid(self, ps_out):
ps_lines = ps_out.readlines()
for ps_line in ps_lines:
ps_items = ps_line.split(" ")
if len(ps_items) == 0:
return None
count = 0
for ps_item in ps_items:
if ps_item is not '':
count = count + 1
if count is 2:
return ps_item
return None
"""
:解析应用CPU
"""
def _find_cpu(self, top_out):
for line in top_out.readlines():
if "user" in line:
items = line.split(" ")
for item in items:
if "user" in item:
parts = item.split("%")
return parts[0]
return None
"""
:解析应用CPU(设备端)
"""
def _find_cpu_8937(self, top_out):
top_lines = top_out.readlines()
top_items = top_lines[4].split(" ")
count = 0
for top_item in top_items:
if top_item is not '':
count = count + 1
if count is 5:
return (int)(top_item.split("%")[0])
return None
"""
:解析应用USS
:USS- Unique Set Size 进程独自占用的物理内存
"""
def _find_uss(self, procrank_out):
procrank_items = procrank_out.split(" ")
count = 0
for procrank_item in procrank_items:
if procrank_item is not '':
count = count + 1
if count is 5:
return (int) (procrank_item.split("K")[0])
return None
"""
:获取CPU占用
"""
def getCpu(user_pid):
print("running get cpu...")
user_total_cpu = 0
user_cpu = 0
if AdbUtil.USER_DEVICE_TYPE is AdbUtil.USER_DEVICE_8937:
for num in range(0, AdbUtil.USER_CPU_TEST_COUNT):
top_out = os.popen(Cmd.CMD_TOP_8937)
user_total_cpu = user_total_cpu + AdbUtil._find_cpu_8937(AdbUtil, top_out)
user_cpu = user_total_cpu / AdbUtil.USER_CPU_TEST_COUNT
print(user_cpu)
elif AdbUtil.USER_DEVICE_TYPE is AdbUtil.USER_DEVICE_PHONE:
for num in range(0, AdbUtil.USER_CPU_TEST_COUNT):
top_out = os.popen(Cmd.CMD_TOP % user_pid)
user_total_cpu = user_total_cpu + AdbUtil._find_cpu(util.AdbUtil, top_out)
user_cpu = user_total_cpu / AdbUtil.USER_CPU_TEST_COUNT
print(user_cpu)
"""
:获取内存占用
"""
def getMemory():
print("running get memory...")
user_total_memory = 0
user_memory = 0
if AdbUtil.USER_DEVICE_TYPE is AdbUtil.USER_DEVICE_8937:
for num in range(0, AdbUtil.USER_MEMORY_TEST_COUNT):
procrank_out = os.popen(Cmd.CMD_PROCRANK).read()
print(procrank_out)
user_total_memory = user_total_memory + AdbUtil._find_uss(AdbUtil, procrank_out)
user_memory = user_total_memory / AdbUtil.USER_MEMORY_TEST_COUNT
print(user_memory)
"""
:测试CPU+内存占用
"""
ps_out = os.popen(Cmd.CMD_PS)
user_pid = AdbUtil._find_pid(AdbUtil, ps_out)
if user_pid is None:
print("application is not running")
else:
getCpu(user_pid)
getMemory()