Linux: How to put a load on system memory?

后端 未结 12 2118
清酒与你
清酒与你 2021-02-10 07:54

I\'m working on a small function, that gives my users a picture of how occupied the CPU is.

I\'m using cat /proc/loadavg, which returns the well known 3 num

12条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-10 08:24

    To eat up a fixed amount of RAM, you could just:

    #include 
    #include 
    #define UNIX 1
    
    //remove the above line if running under Windows
    
    #ifdef UNIX
        #include 
    #else
        #include 
    #endif
    
    int main(int argc, char** argv)
    {
        unsigned long mem;
        if(argc==1)
            mem = 1024*1024*512; //512 mb
        else if(argc==2)
            mem = (unsigned) atol(argv[1]);
        else
        {
            printf("Usage: loadmem ");
            exit(1);
        }
    
        char* ptr = malloc(mem);
        while(1)
        {
            memset(ptr, 0, mem);
            #ifdef UNIX
                sleep(120);
            #else
                Sleep(120*1000);
            #endif
        }
    }
    

    The memset() call seems to be required, because at least on OS X, the actual memory doesn't seem to get used until it is actually initialised.

    EDIT: Fixed in response to comment

提交回复
热议问题