How to Get Current CPU and Ram Usage in C++

How to get current CPU and RAM usage in C++?

There is an open source library that gives these (and more system info stuff) across many platforms: SIGAR API

I've used it in fairly large projects and it works fine (except for certain corner cases on OS X etc.)

Get CPU and RAM usage

There is nothing wrong with your values.

The reason you see differences with what task manager returns is that the "CPU usage" value is something computed for a given interval, i.e. between two NextValue() calls. If task manager "doesn't call its own NextValue" (if we simplify how it works) at the same time you do, you won't return the same results.

Imagine the following scenario:

Time 0: 0% actual CPU usage
Time 1: 50% actual CPU usage
Time 2: 70% actual CPU usage
Time 3: 2% actual CPU usage
Time 4: 100% actual CPU usage
  • If you check the value between Time 1 and Time 3, you'll return something based on "50% and 2%".
  • If task manager checks the value between Time 2 and Time 4, it'll return something different, i.e. a value based on "70% and 100%".

You could try to spawn multiple processes of your own application, you should also see different results.

How to get the total 'percentage' of RAM in C++?

You need to call GlobalMemoryStatusEx to get the data.

MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);

// it already contains the percentage
auto memory_load = statex.dwMemoryLoad;

// or calculate it from other field if need more digits.
auto memory_load = 1 - (double)statex.ullAvailPhys / statex.ullTotalPhys;

note: you should check the return value of GlobalMemoryStatusEx in case it fail.



Related Topics



Leave a reply



Submit