2

I had wrote a program as below which allocated about 1.2G memory at once, and I tested it on Linux. Then I found

  1. If I defined the macro *WRITE_MEM*, the physical memory usage (inspected by the command top) will increase linearly.
  2. If I didn't define the macro, the physical memory usage is very small (about hundreds of kilobytes) and not changed verly large.

I dont's understand the phenomenon.

#include <iostream>  
#include <cmath>  
#include <cstdlib>  

using namespace std;  
float sum = 0.;  

int main (int argc, char** argv)  
{  
    float* pf = (float*) malloc(1024*1024*300*4);  
    float* p = pf;  
    for (int i = 0; i < 300; i++) {  
        cout << i << "..." << endl;  
        float* qf = (float *) malloc(1024*1024*4);  
        float* q = qf;  
        for (int j = 0; j < 1024*1024; j++) {  
            *q++ = sin(j*j*j*j) ;  
        }  
        q = qf;  
        for (int j = 0; j < 1024*1024; j++) {  
#ifdef WRITE_MEM // The physical memory usage will increase linearly
            *p++ = *q++;  
            sum += *q;  
#else            // The physical memory usage is small and will not change
            p++;   
            // or  
            // sum += *p++;  
#endif  
        }  
        free(qf);  
    }  
    free(pf);  
    return 0;  
}  
4

1 回答 1

4

Linux allocates virtual memory immediately, but doesn't back it with physical memory until the pages are actually used. This causes processes to only use the physical memory they actually require, leaving the unused memory available for the rest of the system.

于 2012-09-30T01:49:43.210 回答