using System;
using System.Diagnostics;
using System.Threading;
public class CpuLoadInfo
{
//性能计数器
private static PerformanceCounter pc = new PerformanceCounter();
/// <summary>
/// 得到CPU占用时间的百分比
/// </summary>
/// <returns>返回CPU占用时间的百分比</returns>
public static float getCPUInUsedRate()
{
pc.CategoryName = "Processor";
pc.CounterName = "% Processor Time";
pc.InstanceName = "_Total";
pc.ReadOnly = true;
return pc.NextValue();
}
public static float getMemoryAuailable()
{
pc.CategoryName = "Memory";
pc.CounterName = "Available MBytes";
pc.ReadOnly = true;
return pc.NextValue();
}
public static float getMemoryCommitted()
{
pc.CategoryName = "Memory";
pc.CounterName = "CommittedBytes";
pc.ReadOnly = true;
return pc.NextValue() / (1024 * 1024);
}
public static float getMSMQMessagesMBytes(string sInstanceName)
{
pc.CategoryName = "MSMQ Queue";
pc.CounterName = "Bytes in Queue";
pc.InstanceName = sInstanceName;
pc.ReadOnly = true;
try
{
return pc.NextValue() / (1024 * 1024);
}
catch (Exception ex)
{
return 0;
}
}
public static float getMSMQSerives()
{
return 0;
}
[STAThread]
public static void Main()
{
//PerformanceCounterCategory.Create(("Processor", "% Processor Time", "_Total");
PerformanceCounter pc1
= new PerformanceCounter();
// pc.MachineName ="172.10.100.201";
pc1.CategoryName = "MSMQ Queue";
pc1.CounterName = "Bytes in Queue";
pc1.InstanceName = Environment.MachineName+"//private$//coreexchange";
pc1.ReadOnly = true;
PerformanceCounter pc2
= new PerformanceCounter();
// pc.MachineName ="172.10.100.201";
pc2.CategoryName = "Memory";
pc2.CounterName = "System Driver Total Bytes";
// pc2.InstanceName = "_Total";
pc2.ReadOnly = true;
while (true)
{
float cpuLoad1,cpuLoad2;
Thread.Sleep(1000); // wait for 1 second
cpuLoad1 = pc1.NextValue();
cpuLoad2 = pc2.NextValue();
//Console.WriteLine("CPU load = " + cpuLoad1 / (1024 * 1024));
Console.WriteLine(cpuLoad2 / (1024 * 1024));
// Console.WriteLine(getCPUInUsedRate());
}
}
private const string CategoryName = "Process";
private const string CounterName = "Private Bytes";
private const string InstanceName = "mqsvc";
}