/// <summary> /// Calculate CPU usage, e.g.: this process time vs system process time /// return the CPU usage in percentage /// </summary> 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); }
public static SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[] QuerySystemProcessorPerformanceInfomation(int processorCount) { int len = Marshal.SizeOf(typeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)) * processorCount; IntPtr ptr = Marshal.AllocCoTaskMem(len); UInt32 outLen; NtQuerySystemInformation( SYSTEM_INFORMATION_CLASS.SystemProcessorPerformanceInformation, ptr, (UInt32)len, out outLen ); SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[] list = new SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[processorCount]; for (int i = 0; i < processorCount; i++) { IntPtr p = new IntPtr(ptr.ToInt32() + Marshal.SizeOf(typeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)) * i); list[i] = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)Marshal.PtrToStructure(p, typeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)); } return(list); }