CPU usage programmatically

By | July 1, 2019

Do you know what does it mean when some tool shows percentage of CPU usage, for example 60%? Basically this indicates that during some timing interval 60% of time processor spent on execution of some software code and 40% did nothing or was in idle state. Usually CPU timing is divided into 3 main categories: system, user and idle. System is amount of CPU time used by the kernel, user time related to user processes and idle shows time when processor was not actively being used. Normally CPU in Unix based systems usage percentage is calculated as system plus user times divided by total time (system plus user plus idle times). In Windows CPU timing categories are: kernel (system plus idle of Unix classification), idle and user.

How to get CPU metrics programmatically? There special system API which may be used to retrieve these data: for example NtQuerySystemInformation function in Windows or host_processor_info for Mac OSX.

Generally these API functions are very bad documented and nobody knows how accurate they. During several years Microsoft warns that NtQuerySystemInformation will be deprecated and removed, however this function is still part of Windows system API and no alternative is presented.

Microsoft WMI has special classes for example Win32_Processor which has property LoadPercentage to represent processor load capacity, averaged to the last second however. It is not clear what system API this class uses. The c# Win32_Processor example may be found here.
Processor may have several cores and every core has its own system, user and idle data.
Besides some models of CPU timing take into consideration additional categories such as nice which also relates to user tasks which have below than normal priority.
The C++ example code for Mac OSX platform which calculates average CPU usage during previous seconds specified as argument value is here, the output looks like:


# ./cpuusage 60
Waiting for 60 seconds
Average CPU during last 3 seconds is 0.499168%
# ./cpuusage 3
Waiting for 3 seconds
Average CPU during last 3 seconds is 10.541666%
#

The C++ example code for Windows which calculates average CPU usage per core and for whole processor during previous seconds specified as argument value is here, the output is:

Leave a Reply

Your email address will not be published. Required fields are marked *