Preface
In embedded linux development board, memory and other resources are often limited. It is often necessary to query how much memory the program consumes. linux commands such as "free-m" can only query static residual memory. In other words, these commands do not query the real-time memory consumed by the program's running process.
code implementation
So a better and accurate way is to call the linux system API in the program code to get the remaining memory, through which the maximum memory needed in the real-time running of the program can be known.
There are usually two ways to get the remaining memory in code:
One is to call the pipeline interface. The sample code is as follows:
fp=popen("cat /proc/meminfo | grep MemTotal:|sed -e 's/.*:[^0-9]//'","r"); if(fp < 0) { printf("Unable to read ram information\n"); exit(1); }
The other is to call the sysinfo interface. The sample code is as follows:
#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); }
Result analysis
Following is the result of the second method running:
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
As can be seen from the above results, the maximum (peak) memory value required during the running of the program is 219029504 - 158969856 = 60059648/(1024 * 1024) approximately = 57.277MB.