tags:

views:

354

answers:

3

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?

+3  A: 

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
This code doesn't define Processor and quantity of RAM. It shows how much RAM(Processor) are available(used) now.
Pavel Belousov
+1  A: 

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: http://stackoverflow.com/questions/105031/c-how-do-you-get-total-amount-of-ram-the-computer-has

KevenK
Thanks, I used this code for the CPU speed.
edude05
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
A: 

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!

giddy