Obter uso da CPU e RAM
Preciso obter a memória RAM e o uso da CPU durante a execução de um processo (o processo pode ser executado algumas vezes e mais de 30 minutos). Consigo obter a RAM livre, mas o uso da CPU não está correto, comparado com o valor do gerenciador de tarefas. Estou fazendo algo errado? Aqui está o meu código:
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);
}
}
Mas quando executo o programa, eis o que é impresso no console, comparado com os valores do gerenciador de tarefas:
O que estou fazendo errado?