绘制Linux/Android设备的内存动态变化趋势图

1.生成可执行文件收集动态内存数据

\hardware\qcom\memory\memory_detect.c

#include <stdio.h>
#include <linux/kernel.h>
#include <linux/unistd.h>
#include <unistd.h> 
#include <sys/sysinfo.h>
#include <string.h>   
#include <stdlib.h>  


int main(int argc,char *argv[])
{
	FILE * mfd;
	FILE * rfd;	  
    char buff[1024];
    long total;
    long avalable;
    long free;
    float memory_ratio;
    char name[20];
    char sf[7];
    int interval = 0;
		
		if(argc > 1)
		{
			//char* 到 int
			interval = (int)atoi(argv[1]);
			printf("arg_num : %d,interval : %d\n",argc,interval);
		}else{
			//default 60s
			interval = 60;
		}
		
		system("rm -rf /data/memory.txt"); 
		rfd = fopen("/data/memory.txt","ab+");
		sprintf(sf,"%d",interval);
		fwrite(sf,1,1,rfd);
		fclose(rfd);
		
		while(1)
		{
			avalable = 0;
			free = 0;
			mfd = fopen("/proc/meminfo","r");
			rfd = fopen("/data/memory.txt","ab+");
			fgets(buff, sizeof(buff), mfd); 
		  	sscanf(buff, "%s %ld", name,&total);  
		    fgets(buff, sizeof(buff), mfd); 
		    sscanf(buff, "%s %ld", name,&free); 
		    fgets(buff, sizeof(buff), mfd); 
		    sscanf(buff, "%s %ld", name,&avalable); 
		    printf("total : %ld,avalable : %ld\n",total,avalable);
		    memory_ratio = (float)avalable/(float)total;
		    sprintf(sf,"\n%.3f",memory_ratio); // float 到 char
		    printf("memory ratio:%s\n",sf);
		    fwrite(sf,1,sizeof(sf)-1,rfd);
		    fclose(mfd);
		    fclose(rfd);
		    sleep(interval);
		}
    
}

Android.mk

LOCAL_PATH := $(call my-dir)

# common include paths


# 
include $(CLEAR_VARS)
LOCAL_C_INCLUDES := $(commonIncludes)

LOCAL_MODULE := memory_detect
LOCAL_MODULE_OWNER := qti


LOCAL_SRC_FILES := memory_detect.c

LOCAL_CFLAGS := -D_GNU_SOURCE

LOCAL_PRELINK_MODULE := false
LOCAL_MODULE_TAGS := optional
LOCAL_PROPRIETARY_MODULE := true
include $(BUILD_EXECUTABLE)

之后推送到目标机,执行memory_detect 10 &后台执行即可(每隔10s收集一次剩余内存的比率)。待收集到足够的数据后,取出内存数据/data/memory.txt

2.使用matplotlib绘制内存变化的趋势图,python的脚本memory.py如下:

import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
y_values = []

file = open("memory.txt")
line = file.readline()
interval = int(line)
print interval

line = file.readline()
while line:
    line = float(line)
    print line
    y_values.append(line)
    line = file.readline()

x_values = []
for i in range(len(y_values)):
    x_values.append(i*interval)

plt.scatter(x_values, y_values, s=40)
plt.title("memory usage tendency", fontsize=24)
plt.xlabel("times", fontsize=14)
plt.ylabel("memory usage ratio", fontsize=14)
plt.axis([0, len(x_values*interval), 0, 1.0])
plt.tick_params(axis='both', labelsize=14)
plt.show()

说明:memory_detect进程采集的第一个数据是每次数据收集的间隔时间(单位秒)
3.查看内存变化趋势图
在这里插入图片描述
从上图中,能够很清晰的看出每隔2s采集的内存数据,剩余内存基本都维持在0.6左右

相关推荐
©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页