public static double GetCPUUsage()
{
double ret = 0.0;
//retrieve process time
ProcessTimes processTimes = GetProcessTimes();
UInt64 currentProcessTime = processTimes.KernelTime + processTimes.UserTime;
//retrieve system time
// get number of CPU cores, then, check system time for every CPU core
if(numberOfProcessors == 0 )
{
SystemInfo info;
GetSystemInfo(out info);
Debug.WriteLine(info.NumberOfProcessors);
numberOfProcessors = info.NumberOfProcessors;
}
int size =System.Runtime.InteropServices.Marshal.SizeOf<SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION>();
size = (int) (size * numberOfProcessors);
IntPtr systemProcessInfoBuff = Marshal.AllocHGlobal(size); // should be more than adequate
uint length = 0;
NtStatus result = NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS.SystemProcessorPerformanceInformation, systemProcessInfoBuff, (uint)size, out length);
if (result != NtStatus.Success)
{
Debug.WriteLine($"Failed to obtain processor performance information ({result})");
return ret;
}
UInt64 currentSystemTime = 0;
var systemProcInfoData = systemProcessInfoBuff;
for (int i = 0; i < numberOfProcessors; i++)
{
SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION processPerInfo = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)Marshal.PtrToStructure<SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION>(systemProcInfoData);
currentSystemTime += processPerInfo.KernelTime + processPerInfo.UserTime;
}
//we need to at least measure twice
if (previousProcessTime != 0 && previousSystemTIme != 0)
{
ret = ((double)(currentProcessTime - previousProcessTime) / (double)(currentSystemTime - previousSystemTIme)) * 100.0;
}
previousProcessTime = currentProcessTime;
previousSystemTIme = currentSystemTime;
Debug.WriteLine($"CPU usage: {ret}%");
return ret;
}