How to get CPU frequency in c#

我们两清 提交于 2019-11-28 23:56:08
 var searcher = new ManagementObjectSearcher(
            "select MaxClockSpeed from Win32_Processor");
 foreach (var item in searcher.Get())
 {
      var clockSpeed = (uint)item["MaxClockSpeed"];
 }

if you wish to get other fields look at class Win32_processor

Try this code

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"]);
   }
}

One could take the information out of the registry, but dunno if it works on Windows XP or older (mine is Windows 7).

HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/CentralProcessor/0/ProcessorName 

reads like

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

for me.

Something like this code could retrieve the information (not tested):

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

(source: here)

You can get it via WMI, but it's quite slow so if you're going to be getting it on more than one occasion I'd suggest you cache it - something like:

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;
            }
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!