How to get CPU frequency in c#

前端 未结 5 658
自闭症患者
自闭症患者 2020-12-03 09:17

How can I get in c# the CPU frequency (example : 2Ghz) ? It\'s simple but I don\'t find it in the environnement variables. Thanks :)

5条回答
  •  再見小時候
    2020-12-03 09:30

    If you want to get the turbo speed, you can make use of the "% Processor Performance" performance counter and multiply it with the WMI "MaxClockSpeed" as follows:

    private string GetCPUInfo()
    {
      PerformanceCounter cpuCounter = new PerformanceCounter("Processor Information", "% Processor Performance", "_Total");
      double cpuValue = cpuCounter.NextValue();
    
      Thread loop = new Thread(() => InfiniteLoop());
      loop.Start();
    
      Thread.Sleep(1000);
      cpuValue = cpuCounter.NextValue();
      loop.Abort();
    
      foreach (ManagementObject obj in new ManagementObjectSearcher("SELECT *, Name FROM Win32_Processor").Get())
      {
        double maxSpeed = Convert.ToDouble(obj["MaxClockSpeed"]) / 1000;
        double turboSpeed = maxSpeed * cpuValue / 100;
        return string.Format("{0} Running at {1:0.00}Ghz, Turbo Speed: {2:0.00}Ghz",  obj["Name"], maxSpeed, turboSpeed);
      }
    
      return string.Empty;
    }
    

    The InfiniteLoop method is simply an integer that gets 1 added and subtracted:

    private void InfiniteLoop()
    {
      int i = 0;
    
      while (true)
        i = i + 1 - 1;
    }
    

    The InfiniteLoop method is just added to give the CPU something to do and turbo in the process. The loop is allowed to run for a second before the next value is taken and the loop aborted.

提交回复
热议问题