controlling CPU utilization

后端 未结 2 1614
有刺的猬
有刺的猬 2021-01-06 06:08

how is it advisable to control the cpu utilization during run time ?

poll the cpu load and insert sleeps ?

相关标签:
2条回答
  • 2021-01-06 06:22

    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.

    0 讨论(0)
  • 2021-01-06 06:37

    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.

    0 讨论(0)
提交回复
热议问题