新年第一天,希望在新年裡認識更多朋友,互相學習,共同進步。今天用C語言實作一個Memory負載的壓力測試程式.
點選(此處)折疊或打開
#include stdio.h>
#include stdlib.h>
#include string.h>
#define PAGE_SZ (112)
int main() {
int i;
int gb = 1; //以GB為機關配置設定記憶體大小
for (i = 0; i ((unsigned long)gb30)/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%.
這個方法在模拟記憶體負載時,做壓力測試還是比較有用處的,是以分享一下.