点击(此处)折叠或打开
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
#define PAGE_SZ (1<<12)
-
-
int main() {
-
int i;
-
int gb = 1; //以GB为单位分配内存大小
-
-
for (i = 0; i < ((unsigned long)gb<<30)/PAGE_SZ ; ++i) {
-
void *m = malloc(PAGE_SZ);
-
if (!m)
-
break;
-
memset(m, 0, 1);
-
}
-
printf("allocated %lu MB\n", ((unsigned long)i*PAGE_SZ)>>20);
-
getchar();
-
return 0;
- }
系统当前的内存大小为1.2G.
查看当前系统内存的动态变化状态,1.2G大约使用了148M左右.
编译程序后执行再观察,程序中允许分配的内存为1GBi=1024MBi,发现30s内CPU和内存的负载均达到了最大,监控中看到内存占用了1.1G,约1.2G的91.8%.
这个方法在模拟内存负载时,做压力测试还是比较有用处的,所以分享一下.