Skip to content
March 6, 2010 / kiranpatils

How to get CPU Usage/Memory Usage/Physical Memory

Here are the few functions which will help you out in getting CPU Usage, Memory Usage and Physical Memory Using C#.NET[Proprietor: Yogesh Patel]:


/// <summary>
 /// Gets CPU Usage in %
 /// </summary>
 /// <returns></returns>
 private double getCPUUsage()
 {
 ManagementObject processor = new ManagementObject("Win32_PerfFormattedData_PerfOS_Processor.Name='_Total'");
 processor.Get();

 return double.Parse(processor.Properties["PercentProcessorTime"].Value.ToString());
 }

 /// <summary>
 /// Gets memory usage in %
 /// </summary>
 /// <returns></returns>
 private double getMemoryUsage()
 {
 double memAvailable, memPhysical;

 PerformanceCounter pCntr = new PerformanceCounter("Memory", "Available KBytes");
 memAvailable = (double) pCntr.NextValue();

 memPhysical = getPhysicalMemory();

 return (memPhysical - memAvailable) * 100 / memPhysical;
 }

 /// <summary>
 /// Gets total physical memory
 /// </summary>
 /// <returns></returns>
 private double getPhysicalMemory()
 {
 ObjectQuery winQuery = new ObjectQuery("SELECT * FROM Win32_LogicalMemoryConfiguration");
 ManagementObjectSearcher searcher = new ManagementObjectSearcher(winQuery);

 double memory = 0;
 foreach (ManagementObject item in searcher.Get())
 {
 memory = double.Parse(item["TotalPhysicalMemory"].ToString());
 }
 return memory;
 }

Please note that on INTERNET there are so many functions available but this is most accurate and perfect. We are using it on our production servers.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: