Friday, February 05, 2016

CPU and Memory Usage in C#

using System;
using System.Management;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("root\\CIMV2",
                                                 "SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation WHERE NOT Name='_Total'");
                ManagementObjectSearcher searcher2 =
                    new ManagementObjectSearcher("root\\CIMV2",
                                                 "SELECT * FROM Win32_OperatingSystem");
                for(int c=0; c<15; c++)
                {
                    for (var i = searcher.Get().GetEnumerator(); i.MoveNext();)
                    {
                        string ts = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss.fffffff");
                        ManagementObject queryObj = (ManagementObject)i.Current;
                        Console.WriteLine("Core {0} running at {1} % on {2}", queryObj["Name"], queryObj["PercentProcessorTime"], ts);
                    }
                    for (var i = searcher2.Get().GetEnumerator(); i.MoveNext();)
                    {
                        ManagementObject queryObj = (ManagementObject)i.Current;
                        double free = Double.Parse(queryObj["FreePhysicalMemory"].ToString());
                        double total = Double.Parse(queryObj["TotalVisibleMemorySize"].ToString());
                        Console.WriteLine("Amount used: {0} GB", (total - free)/(1024*1024));
                        Console.WriteLine("Percentage used: {0}%", Math.Round(((total - free) / total * 100), 2));
                    }
                    Console.WriteLine();
                }
                Console.WriteLine("Press any key to continue . . . ");
                Console.ReadKey(true);
            }
            catch (ManagementException e)
            {
                Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}