前言
在嵌入式linux开发板中,内存等资源往往是有限的。经常需要查询程序所耗费的内存多大。 “free -m”等linux命令只能查询静态的剩余内存。换句话,这些命令不能查询程序运行过程实时所消耗的内存。
代码实现
所以一个较好且准确的做法,就是在程序代码调用linux系统API来获取剩余内存,通过剩余内存值得变化就能获知程序实时运行过程中所需要得最大内存。
代码中获取剩余内存往往有两种做法:
一种是调用管道接口,示例代码如下:
fp=popen("cat /proc/meminfo | grep MemTotal:|sed -e 's/.*:[^0-9]//'","r");
if(fp < 0)
{
printf("无法读取ram信息\n");
exit(1);
}
另外一种则是调用 sysinfo接口来实现。示例代码如下:
#include <stdio.h>
#include <linux/kernel.h>
#include <linux/unistd.h>
#include <sys/sysinfo.h>
int main(void)
{
struct sysinfo s_info;
int error = sysinfo(&s_info);
printf("error0: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
func_call1(pcModelName);
error = sysinfo(&s_info);
printf("error1: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
int msg[500];
for (int i = 0; i < 1; i++)
{
func_call2(pcSrcFile, msg);
error = sysinfo(&s_info);
printf("error2: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
func_call3(pcSrcFile, msg);
error = sysinfo(&s_info);
printf("error3: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
}
func_call4();
error = sysinfo(&s_info);
printf("error4: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
}
结果分析
下面是第二种方法运行后的结果:
error0: 0, total: 256958464 free: 219029504
xxx xxx
error2: 0, total: 256958464 free: 159387648
xxx xxx
error3: 0, total: 256958464 free: 158969856
xxx xxx
error4: 0, total: 256958464 free: 163442688
通过上面结果可以知道, 该程序运行过程中,需要得最大(峰值)内存值为 219029504 - 158969856 = 60059648/(1024*1024) 约= 57.277MB