how is it advisable to control the cpu utilization during run time ?
poll the cpu load and insert sleeps ?
The easiest way would be to modify your main loop to either wait on input - the classic event driven model - or to periodically sleep for a short period of time.
If putting the application to sleep I would only use a very short timeout, somewhere within 10-100ms range as any more and some user input would be delayed, and any less would involve a lot more OS level overhead in switching your application.
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.