how is it advisable to control the cpu utilization during run time ?
poll the cpu load and insert sleeps ?
I'd recommend OS functionality. There are performance counters and WinAPI functions for this on Windows.
Here is an example using performance counters from BCL Team Blog:
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());
}
}
This code makes the same with WMI from CodeProject:
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);;
}
So you can query these OS providers (or others for your OS) and sleep your thread if processor utilization is high.