public string f()
Most important thing to do is sample these performance counters at the same rate as Task Manager does. Particularly so for % Idle Time
, a number that has a granularity of 1/64 seconds. Be sure to use a Timer or DispatcherTimer, set its Interval to 1000.
... new PerformanceCounter("Processor", "% Idle Time", "_Total")
You need to use a different counter, category "Processor Information". This counter uses a subtly different strategy to measuring performance, it tries to compensate for the unequal behavior of hyper-threaded cores and the side-effects of processor clock frequency throttling. Difference is about ~4% on my machine. Beware that it is hard to get an exact match, the number changes quickly and you are only exactly in sync with Task Manager's sampling times by accident.
... new PerformanceCounter("Memory", "Available MBytes")
To convert it to percent you need to subtract this number from the total amount of physical RAM available. You can get this number from ComputerInfo.TotalPhysicalMemory as demonstrated in this post. If you don't want to use this namespace, common complaint, then you have to pinvoke GlobalMemoryStatusEx().
Code I used to verify these changes:
private void timer1_Tick(object sender, EventArgs e) {
label1.Text = IdleCounter.NextValue().ToString("N0");
double total = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
var used = 1024.0 * 1024.0 * RamCounter.NextValue();
label2.Text = (100.0 * (total - used) / total).ToString("N0");
}