我一直试图摆脱使用PerformanceCounter类来监控进程的CPU使用情况,因为当进程计数变得非常高时(监视大量进程时)它似乎需要相当数量的CPU )。
我的第一种方法是使用Win32_PerfFormattedData_PerfOS_Processor类和PercentProcessorTime属性来获取WMI路由,但是在尝试计算多个核心的CPU使用率时似乎存在问题(它返回的最大值为100%)因此无法根据CPU核心数进行划分,从而导致结果不准确。)
所以最后我决定使用Process的类TotalProcessorTime属性。遗憾的是,我不确定如何根据该值计算Process使用的总CPU使用百分比。我知道我应该从之前的PercentProcessorTime值中减去当前的PercentProcessorTime值,以获得处理器在特定时间限制内花费的时间,但我不确定如何从那里继续。
提前致谢。
答案 0 :(得分:16)
class GetCPUUsage
{
static TimeSpan start;
public static double CPUUsageTotal
{
get;
private set;
}
public static double CPUUsageLastMinute
{
get;
private set;
}
static TimeSpan oldCPUTime = new TimeSpan(0);
static DateTime lastMonitorTime = DateTime.UtcNow;
public static DateTime StartTime = DateTime.UtcNow;
// Call it once everything is ready
static void OnStartup()
{
start = Process.GetCurrentProcess().TotalProcessorTime;
}
// Call this every 30 seconds
static void CallCPU()
{
TimeSpan newCPUTime = Process.GetCurrentProcess().TotalProcessorTime - start;
CPUUsageLastMinute = (newCPUTime - oldCPUTime).TotalSeconds / (Environment.ProcessorCount * DateTime.UtcNow.Subtract(lastMonitorTime).TotalSeconds);
lastMonitorTime = DateTime.UtcNow;
CPUUsageTotal = newCPUTime.TotalSeconds / (Environment.ProcessorCount * DateTime.UtcNow.Subtract(StartTime).TotalSeconds);
oldCPUTime = newCPUTime;
}
}
class GetCPUInfo
{
public static string GetInfoMinute()
{
return String.Format("{0:0.0}", GetCPUUsage.CPUUsageLastMinute * 100);
}
public static string GetInfoTotal()
{
return String.Format("{0:0.0}", GetCPUUsage.CPUUsageTotal * 100);
}
}
答案 1 :(得分:0)
基于111WARLOCK111的答案,您可以使用以下最少的代码来衡量当前的CPU负载:
async Task<double> GetCpuLoadAsync(TimeSpan MeasurementWindow)
{
Process CurrentProcess = Process.GetCurrentProcess();
TimeSpan StartCpuTime = CurrentProcess.TotalProcessorTime;
Stopwatch Timer = Stopwatch.StartNew();
await Task.Delay(MeasurementWindow);
TimeSpan EndCpuTime = CurrentProcess.TotalProcessorTime;
Timer.Stop();
return (EndCpuTime - StartCpuTime).TotalMilliseconds / (Environment.ProcessorCount * Timer.ElapsedMilliseconds);
}
使用以下代码调用该函数,并将TimeSpan替换为要监视的窗口:
double CpuLoad = await GetCpuLoadAsync(TimeSpan.FromSeconds(10));