如何在c#中获取CPU频率

时间:2011-08-03 08:40:49

标签: c# cpu frequency

如何获得c#的CPU频率(例如:2Ghz)? 这很简单,但我没有在环境变量中找到它。 谢谢:))

5 个答案:

答案 0 :(得分:12)

 var searcher = new ManagementObjectSearcher(
            "select MaxClockSpeed from Win32_Processor");
 foreach (var item in searcher.Get())
 {
      var clockSpeed = (uint)item["MaxClockSpeed"];
 }

如果您希望其他字段查看课程Win32_processor

答案 1 :(得分:5)

试试此代码

using System.Management;

uint currentsp , Maxsp;
public void CPUSpeed()
{
   using(ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'"))
   {
       currentsp = (uint)(Mo["CurrentClockSpeed"]);
       Maxsp = (uint)(Mo["MaxClockSpeed"]);
   }
}

答案 2 :(得分:2)

可以从注册表中获取信息,但是如果它在Windows XP或更早版本(我的是Windows 7)上运行则不知道。

HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/CentralProcessor/0/ProcessorName 

读起来像

Intel(R) Core(TM)2 Quad CPU    Q6600  @ 2.40GHz

对我来说。

像这样的代码可以检索信息(未经测试):

RegistryKey processor_name = Registry.LocalMachine.OpenSubKey(@"Hardware\Description\System\CentralProcessor\0", RegistryKeyPermissionCheck.ReadSubTree);  


if (processor_name != null)
{
  if (processor_name.GetValue("ProcessorNameString") != null)
  {
    string value = processor_name.GetValue("ProcessorNameString");
    string freq = value.Split('@')[1];
    ...
  }
}

(来源:here

答案 3 :(得分:1)

你可以通过WMI获得它,但它很慢,所以如果你不止一次得到它我会建议你缓存它 - 比如:

namespace Helpers
{
    using System.Management;

    public static class HardwareHelpers
    {
        private static uint? maxCpuSpeed = null;
        public static uint MaxCpuSpeed
        {
            get
            {
                return maxCpuSpeed.HasValue ? maxCpuSpeed.Value : (maxCpuSpeed = GetMaxCpuSpeed()).Value;
            }
        }

        private static uint GetMaxCpuSpeed()
        {
            using (var managementObject = new ManagementObject("Win32_Processor.DeviceID='CPU0'"))
            {
                var sp = (uint)(managementObject["MaxClockSpeed"]);

                return sp;
            }
        }
    }
}

答案 4 :(得分:0)

如果要获得加速速度,可以使用“%Processor Performance”性能计数器,并将其与WMI“ MaxClockSpeed”相乘,如下所示:

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;
}

InfiniteLoop方法只是一个整数,该整数得到1加减:

private void InfiniteLoop()
{
  int i = 0;

  while (true)
    i = i + 1 - 1;
}

仅添加了InfiniteLoop方法,以使CPU可以执行一些操作并在处理过程中进行加速。允许循环运行一秒钟,然后再获取下一个值,然后中止循环。