5

I need a simple way of checking how much ram and fast the CPU of the host PC is. I tried WMI however the code I'm using

 private long getCPU()
 {
    ManagementClass mObject = new ManagementClass("Win32_Processor");
    mObject.Get();
    return (long)mObject.Properties["MaxClockSpeed"].Value;

 }

Throws a null reference exception. Furthermore, WMI queries are a bit slow and I need to make a few to get all the specs. Is there a better way?

edude05
  • 744
  • 1
  • 10
  • 23

3 Answers3

6

http://dotnet-snippets.com/dns/get-the-cpu-speed-in-mhz-SID575.aspx

using System.Management;

public uint CPUSpeed()
{
  ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
  uint sp = (uint)(Mo["CurrentClockSpeed"]);
  Mo.Dispose();
  return sp;
}

RAM can be found in this SO question: How do you get total amount of RAM the computer has?

Community
  • 1
  • 1
KevenK
  • 2,975
  • 3
  • 26
  • 33
  • Not sure if "ManagementObject" class is the best way to go as it depends on the Windows Management Instrumentation service. If the service is stopped or not running, your code would not work as expected. I would prefer the Performance Counter approach but would like to know how prevalent usage of ManagementObject is? – Bharath K Jun 16 '10 at 12:20
2

You should use PerformanceCounter class in System.Diagnostics

PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;

cpuCounter = new PerformanceCounter();

cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";

ramCounter = new PerformanceCounter("Memory", "Available MBytes");


public string getCurrentCpuUsage(){
            cpuCounter.NextValue()+"%";
}

public string getAvailableRAM(){
            ramCounter.NextValue()+"MB";
}
Patrice Pezillier
  • 4,476
  • 9
  • 40
  • 50
1

Much about the processor including its speed in Mhz is available under HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor

I'm running 2 Win7x64 pcs and for some reason the WMI query shows a vague number the first time I run the code and the correct processor speed the second time I run it?

When it comes to performance counters, I did work a LOT with the network counters and got in accurate results and eventually had to find a better solution, so I dont trust them!

gideon
  • 19,329
  • 11
  • 72
  • 113
  • You mention that you ended up using a different solution to monitoring network counters. Would you mind sharing what you ended up using? – Jim Scott Sep 28 '16 at 16:45
  • hey @JimScott , haha quite an old story really. The app did some bandwidth monitoring as part of it's job. I believe I noticed the performance counters **for network** was off in instantaneous cases and wrote something that gave me an average of multiple calls over time. Hope that helps in your case. – gideon Oct 01 '16 at 09:36