CPU usage control

How is it advisable to control processor usage at runtime?

to interrogate processor loading and to insert sleeps?

+4
source share
2 answers

I would recommend OS functionality. Windows has performance counters and WinAPI features.

Here is an example of using performance counters from the BCL 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 does 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);; } 

Thus, you can request these OS providers (or others for your OS) and sleep flow if the processor load is high.

+4
source

The easiest way is to change the main loop to either wait at the input — a classic event-driven model or periodically sleep for a short period of time.

If you put the application to sleep, I would use only a very short timeout, somewhere within 10-100 ms, as well as more, and some user input delay would be delayed, and in any case there would be much more cost to the OS level when switching the application.

0
source

All Articles