如何在运行时控制CPU利用率?
轮询CPU负载并插入休眠是可行的吗?
foreach (Process proc in Process.GetProcesses()) {
using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", proc.ProcessName)) {
pcProcess.NextValue();
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Process:{0} CPU% {1}", proc.ProcessName, pcProcess.NextValue());
}
}
这段代码与来自CodeProject的WMI相同:
public string GetCPU()
{
decimal PercentProcessorTime=0;
mObject_CPU.Get();
ulong u_newCPU =
(ulong)mObject_CPU.Properties["PercentProcessorTime"].Value;
ulong u_newNano =
(ulong)mObject_CPU.Properties["TimeStamp_Sys100NS"].Value;
decimal d_newCPU = Convert.ToDecimal(u_newCPU);
decimal d_newNano = Convert.ToDecimal(u_newNano);
decimal d_oldCPU = Convert.ToDecimal(u_oldCPU);
decimal d_oldNano = Convert.ToDecimal(u_oldNano);
// Thanks to MSDN for giving me this formula !
PercentProcessorTime =
(1 - ((d_newCPU-d_oldCPU)/(d_newNano - d_oldNano)))*100m;
// Save the values for the next run
u_oldCPU = u_newCPU;
u_oldNano = u_newNano;
return PercentProcessorTime.ToString("N",nfi);;
}
最简单的方法是修改您的主循环,以等待输入 - 经典的事件驱动模型 - 或定期短暂休眠。
如果将应用程序置于睡眠状态,我只会使用非常短的超时时间,通常在10-100毫秒范围内,因为任何更长的时间都会延迟一些用户输入,而任何更短的时间都会涉及更多的操作系统级别开销来切换您的应用程序。