android手机下内存查看脚本

#!/usr/bin/python3
#  -*- coding:utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import copy
from collections import OrderedDict
import matplotlib.pyplot as plt
import numpy as np
from openpyxl import load_workbook
import subprocess
import re
import sys
import time
import os
import xlwt
from xlrd import open_workbook
from xlutils.copy import copy

#最大记录的次数
MAX=600
#helloar C包名
HELLOARC = "com.standardar.ar.core.examples.c.helloar"
HELLOARJAVA = "com.standardar.ar.core.examples.java.helloar"
ARSERVER = 'com.standardar.ar.core.examples.c.helloar'
CAMERASERVICE = 'cameraserver'
APP = "com.standardar.ar.c+"
APPSERVER = "com.standardar.+"

#获取pid
def get_process_pid(grep_key):
    pid = []
    #pattern = re.compile(r"\d+")
    cmd = 'adb shell \"ps -A| grep %s\"' % grep_key
    data = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    dumpsys = data.stdout.read().decode()
    log = dumpsys.split("\n")
    #print(log)
    if log is not None and len(log) > 1:
        for x in log:
            pid = x.split()[1]
            return pid

def get_process_name():
    cmd = 'adb shell dumpsys window | grep mCurrentFocus'  # mac用grep 、win用findstr
    data = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    dumpsys = data.stdout.read().decode()
    log = re.split("\\s+|/",dumpsys)
    return log[3]


def getCPU(appname):
    cmd = 'adb shell \"top -n 1 -b | grep %s\"' % appname
    #print(cmd)
    log = os.popen(cmd).readlines()
    #print(log)
    #print(len(log))
    if log is not None and len(log) > 0:
        log1 = log[0]
        #print(log1)
        if log1 is not None and len(log1) > 1:
            cpu = log1.split()[8]
           # print(cpu)
            return cpu
    else:
        print(appname + "程序未启动")

#设置表格样式
def set_style(name,height,bold=False):
    style = xlwt.XFStyle() # 初始化样式
    font = xlwt.Font() # 为样式创建字体
    font.name = name # 'Times New Roman'
    font.bold = bold
    font.color_index = 4
    font.height = height
    style.font = font
    return style

#将信息写入excel表格
def write_xls(index, lis, row, filename):
    rb = open_workbook(filename,formatting_info=True)
    wb = copy(rb)
    ws = wb.get_sheet(index)
    #print(lis)
    for col in range(len(lis)):
        ws.write(row, col, float(lis[col]))
    wb.save(filename)


def init():
    style = set_style('Times New Roman',220,True)
    #创建一个表格
    f = xlwt.Workbook(encoding='utf-8', style_compression=0) #创建工作簿
    sheet1 = f.add_sheet('ARServer',cell_overwrite_ok=True) #创建sheet
    if get_process_name()==HELLOARC:
        sheet2 = f.add_sheet('HelloAR_C',cell_overwrite_ok=True)
    else:
        sheet2 = f.add_sheet('HelloAR_Java',cell_overwrite_ok=True)
    #sheet3 = f.add_sheet('CameraServer',cell_overwrite_ok=True)
    third_col=sheet1.col(2)
    third_col.width=256*13
    fourth_col=sheet1.col(3)
    fourth_col.width=256*13

    third_col=sheet2.col(2)
    third_col.width=256*13
    fourth_col=sheet2.col(3)
    fourth_col.width=256*13

    # third_col=sheet3.col(2)
    # third_col.width=256*13
    # fourth_col=sheet3.col(3)
    # fourth_col.width=256*13

    row0 = [u'次数',u'Total PSS',u'Native Heap',u'Java Heap',u'Graphics',u'CPURate']
    for i in range(0,len(row0)):
        sheet1.write(0,i,row0[i],style)
        sheet2.write(0, i, row0[i], style)
        #sheet3.write(0, i, row0[i], style)
    f.save('resource_senseAR.xls')

def getResource(appname, index):
    # 获取内存信息
    cmd = 'adb shell dumpsys meminfo ' + appname
    log = os.popen(cmd).readlines()
    if log is not None and len(log) > 1:
        TOTAL = 0
        Native_Heap = 0
        Java_Heap = 0
        Graphics = 0
        cpurate = 0
        for x in log:
            if "Native Heap:" in x:
                x = x.split()
                Native_Heap = int(x[2])
            if "Java Heap:" in x:
                x = x.split()
                Java_Heap = int(x[2])
            if "Graphics:" in x:
                x = x.split()
                Graphics = int(x[1])
            if "TOTAL:" in x:
                x = x.split()
                TOTAL = int(x[1])

        #name = appname
        # if appname == HELLOARC or appname == HELLOARJAVA:
        #     name = APP
        # elif appname == ARSERVER:
        #     name = APPSERVER
        # cpurate = getCPU(name)
        cpurate = getCPU(appname)
        T = [n, TOTAL, Native_Heap, Java_Heap, Graphics, cpurate]
        write_xls(index, T, n, filename='resource_senseAR.xls')  # 将内存信息写入表格
        time.sleep(3)
    else:
        print(appname + "程序不存在! Exit")
        sys.exit(-1)

def cre_Chat(sheet_name,y_col,fig_name):
    plt.rcParams.update({
    'font.sans-serif' : ['DejaVu Sans Mono'],
    'font.weight': 'normal',
    'font.size': 16,
    'xtick.direction': 'out',
    'xtick.labelsize': 12,
    'ytick.direction': 'out',
    'ytick.labelsize': 12,
    })

    rb = open_workbook("resource_senseAR.xls",formatting_info=True)
    sheet = rb.sheet_by_name(sheet_name)
    data = sheet.col_values(0)
    x = data[1:]
    x_label = data[0]
    data = sheet.col_values(y_col)
    y = data[1:]
    y_label = data[0]

    fig, axes = plt.subplots(figsize=(9.84, 5.9))

    ax = axes.plot(x, y)

    plt.title(y_label)
    plt.grid()

    fig.text(0.18, 0.80, u'Avg: ' + "{:.1f}".format(sum(y)/len(y)), color='black', weight='regular')
    fig.text(0.18, 0.75, u'Max: ' + str(max(y)), color='black', weight='regular')
    fig.text(0.18, 0.70, u'Min: ' + str(min(y)), color='black', weight='regular')

    plt.savefig(fig_name, format='png')
    plt.clf()

init()
n = 1
while n > 0 and n <= MAX:
    cpu_rate_temp = 0
    print("CPU内存测试第%s次......" % n)
    getResource(ARSERVER,0)
    getResource(HELLOARC,1)
    n += 1 
 #cre_Chat("ARServer",1,"TotalPSS_ARserver_C.png")
 #cre_Chat("ARServer",5,"CPUrate_ARserver_C.png")
 #cre_Chat("HelloAR_C",1,"TotalPSS_HelloAR_C.png")
 #cre_Chat("HelloAR_C",5,"CPUrate_HelloAR_C.png")
    #getResource(HELLOARJAVA,1)
    #n += 1
cre_Chat("ARServer",1,"TotalPSS_ARserver_Java.png")
cre_Chat("ARServer",5,"CPUrate_ARserver_Java.png")
cre_Chat("HelloAR_Java",1,"TotalPSS_HelloAR_Java.png")
cre_Chat("HelloAR_Java",5,"CPUrate_HelloAR_Java.png")
    
    #getResource(CAMERASERVICE,2)
    ```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值