我需要在執行進程期間獲取RAM內存和CPU使用情況(該進程有時可以運行超過30分鐘)。我能夠獲得可用的RAM,但CPU使用率不正確,與任務管理器的值相比較。難道我做錯了什麼?這裏是我的代碼:獲取CPU和RAM的使用情況
class Program
{
static List<float> AvailableCPU = new List<float>();
static List<float> AvailableRAM = new List<float>();
protected static PerformanceCounter cpuCounter;
protected static PerformanceCounter ramCounter;
static void Main(string[] args)
{
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
try
{
System.Timers.Timer t = new System.Timers.Timer(1200);
t.Elapsed += new ElapsedEventHandler(TimerElapsed);
t.Start();
Thread.Sleep(10000);
}
catch (Exception e)
{
Console.WriteLine("catched exception");
}
Console.ReadLine();
}
public static void TimerElapsed(object source, ElapsedEventArgs e)
{
float cpu = cpuCounter.NextValue();
float ram = ramCounter.NextValue();
Console.WriteLine(string.Format("CPU Value: {0}, ram value: {1}", cpu, ram));
AvailableCPU.Add(cpu);
AvailableRAM.Add(ram);
}
}
但是當我運行該程序,這裏是它的打印到控制檯,從任務管理器的值進行比較:
我在做什麼錯?
它在顯示屏上波動 - 也許你正在比較不同的時間範圍?你在這裏有一個2.7的值... –
我已經添加了一個方法來模擬cpu的負載,並且這個值甚至與任務管理器中的值沒有接近。我每秒讀一次數值。我懷疑這可能是由於多核心CPU,但我還不確定... –