¿Cómo obtener el uso actual de CPU y RAM en C++?


¿Es posible, en C++, obtener el uso actual de RAM y CPU? ¿Hay una llamada a una función independiente de la plataforma?

Author: BradleyDotNET, 2009-01-26

8 answers

Hay una biblioteca de código abierto que proporciona estos (y más información del sistema) en muchas plataformas: SIGAR API

Lo he usado en proyectos bastante grandes y funciona bien (excepto en ciertos casos de esquina en OS X, etc.).)

 11
Author: ididak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-28 08:40:02

Lamentablemente, estas cosas dependen en gran medida del sistema operativo subyacente, por lo que no hay llamadas independientes de la plataforma. (Tal vez hay algunos marcos de envoltura, pero no conozco ninguno.)

En Linux puede echar un vistazo a la llamada a la función getrusage(), en Windows puede usar GetProcessMemoryInfo() para el uso de RAM. Eche también un vistazo a las otras funciones de la API Process Status de Windows.

 30
Author: Kosi2801,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-26 13:17:40

No hay una función independiente de la plataforma para esto que yo sepa. SI planea dirigirse a varias versiones de Windows, tenga en cuenta que la implementación difiere entre algunas versiones. Me golpeó este problema al probar una aplicación bajo NT 3.51 por ejemplo... (arcaico, lo sé).

Aquí hay un código que usé para el lado de la memoria de las cosas. Esto no funciona en otras plataformas que no sean windows, y solo devolverá 0 cuando se compila sin la definición de WIN32:

EDITAR: Me olvidé de mencione, este código se divide y redondea al MB más cercano, por lo tanto el > > 20 en todo el lugar.

// get memory info...
int getTotalRAM()
{
    int ret = 0;
#ifdef WIN32
    DWORD v = GetVersion();
    DWORD major =  (DWORD)(LOBYTE(LOWORD(v)));
    DWORD minor =  (DWORD)(HIBYTE(LOWORD(v)));
    DWORD build;
    if (v < 0x80000000) build = (DWORD)(HIWORD(v));
    else build = 0;

    // because compiler static links the function...
    BOOL (__stdcall*GMSEx)(LPMEMORYSTATUSEX) = 0;

    HINSTANCE hIL = LoadLibrary(L"kernel32.dll");
    GMSEx = (BOOL(__stdcall*)(LPMEMORYSTATUSEX))GetProcAddress(hIL, "GlobalMemoryStatusEx");

    if(GMSEx)
    {
        MEMORYSTATUSEX m;
        m.dwLength = sizeof(m);
        if(GMSEx(&m))
        {
            ret = (int)(m.ullTotalPhys>>20);
        }
    }
    else
    {
        MEMORYSTATUS m;
        m.dwLength = sizeof(m);
        GlobalMemoryStatus(&m);
        ret = (int)(m.dwTotalPhys>>20);
    }
#endif
    return ret;
}

int getAvailRAM()
{
    int ret = 0;
#ifdef WIN32
    DWORD v = GetVersion();
    DWORD major =  (DWORD)(LOBYTE(LOWORD(v)));
    DWORD minor =  (DWORD)(HIBYTE(LOWORD(v)));
    DWORD build;
    if (v < 0x80000000) build = (DWORD)(HIWORD(v));
    else build = 0;

    // because compiler static links the function...
    BOOL (__stdcall*GMSEx)(LPMEMORYSTATUSEX) = 0;

    HINSTANCE hIL = LoadLibrary(L"kernel32.dll");
    GMSEx = (BOOL(__stdcall*)(LPMEMORYSTATUSEX))GetProcAddress(hIL, "GlobalMemoryStatusEx");

    if(GMSEx)
    {
        MEMORYSTATUSEX m;
        m.dwLength = sizeof(m);
        if(GMSEx(&m))
        {
            ret = (int)(m.ullAvailPhys>>20);
        }
    }
    else
    {
        MEMORYSTATUS m;
        m.dwLength = sizeof(m);
        GlobalMemoryStatus(&m);
        ret = (int)(m.dwAvailPhys>>20);
    }
#endif
    return ret;
}

int getTotalMemory()
{
    int ret = 0;
#ifdef WIN32
    DWORD v = GetVersion();
    DWORD major =  (DWORD)(LOBYTE(LOWORD(v)));
    DWORD minor =  (DWORD)(HIBYTE(LOWORD(v)));
    DWORD build;
    if (v < 0x80000000) build = (DWORD)(HIWORD(v));
    else build = 0;

    // because compiler static links the function...
    BOOL (__stdcall*GMSEx)(LPMEMORYSTATUSEX) = 0;

    HINSTANCE hIL = LoadLibrary(L"kernel32.dll");
    GMSEx = (BOOL(__stdcall*)(LPMEMORYSTATUSEX))GetProcAddress(hIL, "GlobalMemoryStatusEx");

    if(GMSEx)
    {
        MEMORYSTATUSEX m;
        m.dwLength = sizeof(m);
        if(GMSEx(&m))
        {
            ret = (int)(m.ullTotalPhys>>20) + (int)(m.ullTotalVirtual>>20);
        }
    }
    else
    {
        MEMORYSTATUS m;
        m.dwLength = sizeof(m);
        GlobalMemoryStatus(&m);
        ret = (int)(m.dwTotalPhys>>20) + (int)(m.dwTotalVirtual>>20);
    }
#endif
    return ret;
}

int getAvailMemory()
{
    int ret = 0;
#ifdef WIN32
    DWORD v = GetVersion();
    DWORD major =  (DWORD)(LOBYTE(LOWORD(v)));
    DWORD minor =  (DWORD)(HIBYTE(LOWORD(v)));
    DWORD build;
    if (v < 0x80000000) build = (DWORD)(HIWORD(v));
    else build = 0;

    // because compiler static links the function...
    BOOL (__stdcall*GMSEx)(LPMEMORYSTATUSEX) = 0;

    HINSTANCE hIL = LoadLibrary(L"kernel32.dll");
    GMSEx = (BOOL(__stdcall*)(LPMEMORYSTATUSEX))GetProcAddress(hIL, "GlobalMemoryStatusEx");

    if(GMSEx)
    {
        MEMORYSTATUSEX m;
        m.dwLength = sizeof(m);
        if(GMSEx(&m))
        {
            ret = (int)(m.ullAvailPhys>>20) + (int)(m.ullAvailVirtual>>20);
        }
    }
    else
    {
        MEMORYSTATUS m;
        m.dwLength = sizeof(m);
        GlobalMemoryStatus(&m);
        ret = (int)(m.dwAvailPhys>>20) + (int)(m.dwAvailVirtual>>20);
    }
#endif
    return ret;
}
 11
Author: jheriko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-28 16:31:35

No, no hay, no en el estándar.

Si realmente necesita esta información, tendrá que escribir #ifdefs específicos de la plataforma o un enlace contra una biblioteca que la proporcione.

 5
Author: HUAGHAGUAH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-26 13:13:17

En Linux, esto usará /proc/self/status . Se requiere más trabajo para convertir esto en un número. Sin embargo, encuentro esto útil como es, solo para imprimir el uso de memoria directamente en la pantalla como una cadena.

static string memory_usage() {
        ostringstream mem;
        PP("hi");
        ifstream proc("/proc/self/status");
        string s;
        while(getline(proc, s), !proc.fail()) {
                if(s.substr(0, 6) == "VmSize") {
                        mem << s;
                        return mem.str();
                }
        }
        return mem.str();
}
 2
Author: Aaron McDaid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-05 04:59:10

No hay una forma independiente de la plataforma de hacer esto. Aunque para Windows, puede obtener el uso de la CPU y las métricas de rendimiento mediante el uso de PDH.dll (Performance Data Helper) y sus API relacionadas en el código.

Aquí hay más sobre cómo usarlo.

 1
Author: Samrat Patil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-27 08:55:27

No directamente.

Pero puede usar una biblioteca que abstraiga el sistema operativo (como ACE).
Aunque esto podría ser un poco pesado si solo quieres CPU y memoria.

 0
Author: Martin York,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-26 16:41:11

Si ese sigue siendo el caso, compruebe:

Http://sourceforge.net/projects/cpp-cpu-monitor /

Le da un ejemplo de cómo obtener el uso de CPU y RAM de un Linux (probado en Debian y CentOS) y una instrucción bastante simple de cómo instalarlo.

Por favor, siéntase libre de preguntar si tiene alguna pregunta con respecto a este pequeño proyecto.

 0
Author: Bartosz Pachołek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-05 10:52:06