How to get CPU frequency in c#

前端 未结 5 655
自闭症患者
自闭症患者 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:36

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

提交回复
热议问题