#include <sys/resource.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int i = 0;
int totalmem = 0;
struct rusage r_usage;
while (++i <= 10) {
void *m = malloc(20*1024*1024);
memset(m,0,20*1024*1024);
totalmem +=20*1024*1024;
printf("Memory malloc[20MB, %dKB], totalmem=%dB, %dKB, %dMB\n", 20*1024, totalmem, totalmem/1024, totalmem/1024/1024);
getrusage(RUSAGE_SELF,&r_usage);
printf("Memory usage = %ldKB, %ldMB\n",r_usage.ru_maxrss, r_usage.ru_maxrss/1024);
sleep (3);
}
printf("\nAllocated memory, sleeping ten seconds after which we will check again...\n\n");
sleep (10);
getrusage(RUSAGE_SELF,&r_usage);
printf("Memory usage = %ldKB, %ldMB\n",r_usage.ru_maxrss, r_usage.ru_maxrss/1024);
return 0;
}
g++ test.c -o test
./test
Memory malloc[20MB, 20480KB], totalmem=20971520B, 20480KB, 20MB
Memory usage = 21284KB, 20MB
Memory malloc[20MB, 20480KB], totalmem=41943040B, 40960KB, 40MB
Memory usage = 42176KB, 41MB
Memory malloc[20MB, 20480KB], totalmem=62914560B, 61440KB, 60MB
Memory usage = 62504KB, 61MB
Memory malloc[20MB, 20480KB], totalmem=83886080B, 81920KB, 80MB
Memory usage = 83096KB, 81MB
Memory malloc[20MB, 20480KB], totalmem=104857600B, 102400KB, 100MB
Memory usage = 103688KB, 101MB
Memory malloc[20MB, 20480KB], totalmem=125829120B, 122880KB, 120MB
Memory usage = 124016KB, 121MB
Memory malloc[20MB, 20480KB], totalmem=146800640B, 143360KB, 140MB
Memory usage = 144608KB, 141MB
Memory malloc[20MB, 20480KB], totalmem=167772160B, 163840KB, 160MB
Memory usage = 164936KB, 161MB
Memory malloc[20MB, 20480KB], totalmem=188743680B, 184320KB, 180MB
Memory usage = 185528KB, 181MB
Memory malloc[20MB, 20480KB], totalmem=209715200B, 204800KB, 200MB
Memory usage = 206120KB, 201MB
Allocated memory, sleeping ten seconds after which we will check again...
Memory usage = 206120KB, 201MB
http://appcrawler.com/wordpress/2013/05/13/simple-example-of-tracking-memory-using-getrusage/
https://stackoverflow.com/questions/1558402/memory-usage-of-current-process-in-c