1

I'm new here so I apologize if I have posted in the wrong area or am missing some information in my question. Is it possible to poll global memory usage in windows with Qt5? I've searched through the Qt5 Classes and I didn't find anything that I thought would fit the bill. For more specificity, I'm looking for something similar to GlobalMemoryStatusEx.

  • 1
    Seems unlikely, but the version of the Qt documentation you linked to is very old. – MrEricSir Apr 09 '18 at 19:03
  • There is nothing like this in Qt5; see older question [Getting memory information with Qt](https://stackoverflow.com/questions/8122277/getting-memory-information-with-qt) – Ľubomír Carik Apr 11 '18 at 17:07

1 Answers1

1

Qt doesn't offer a portable API to do so, since querying the OS for memory usage is indeed, an OS specific task.

You can however, write a wrapper class, which uses the correct API depending on the OS you are running.

As an example, on Windows you could use the API you have already mentioned (GlobalMemoryStatusEx), while on Linux you could use the sysinfo API).

Once you have identified the APIs to use for the target platforms, you can use conditional compilation to compile only the correct code for each platform, while offering the same interface to the outside world.

Qt offers a few defines (Q_OS_) which are set or not depending on the target OS. Have a look at the documentation here for more details.

Example:

/*!
 * \brief MemoryUsage::getMemoryUsage
 * \return the overall memory usage in percent.
 */
int MemoryUsage::getMemoryUsage()
{
    int result = 0;

#ifdef Q_OS_LINUX
    struct sysinfo sys_info;

    sysinfo(&sys_info);

    unsigned long long total = sys_info.totalram *(unsigned long long)sys_info.mem_unit / 1024;
    unsigned long long free = sys_info.freeram *(unsigned long long)sys_info.mem_unit/ 1024;

    result = (total - free) * 100 / total;
#endif

#ifdef Q_OS_WIN
    MEMORYSTATUSEX statex;
    statex.dwLength = sizeof (statex);

    GlobalMemoryStatusEx (&statex);

    result = statex.dwMemoryLoad);
#endif

    return result;
} 

With the same trick you must also ensure the correct headers are included (e.g. don't include when you are compiling for Linux).

Sergio Monteleone
  • 2,776
  • 9
  • 21