The Adapdev.Diagnostics namespace provides access to system performance metrics. It's primary purpose to assist with nano-second timing and cpu utilization.
The CPUMeter class shows you CPU utilization:
CPUMeter mtr = new CPUMeter();
... // do some heavy lifting
double usage = mtr.GetCpuUtilization();
Console.WriteLine("Done. CPU Usage {0:#00.00} %", usage);
You can also do it for a specific process id:
CPUMeter mtr = new CPUMeter(123);
... // do some heavy lifting
double usage = mtr.GetCpuUtilization();
Console.WriteLine("Done. CPU Usage {0:#00.00} %", usage);
One of the problems with the default timer capabilities in .NET is that it doesn't go down to the exact nano-second level - which is critical for applications such as unit testing - but instead rounds out the milliseconds. Adapdev.Diagnostics provides a class for low-level timing, with the option of several different timer types:
Minutes
Ticks
Seconds (same as Ticks)
Milliseconds
Hi-Res Milliseconds (the most accurate)
Below are examples using the various approaches:
Minutes
IPerfTimer t = PerfTimerFactory.GetPerfTimer(PerfTimerType.MINUTES);
t.Start();
Thread.Sleep(1000);
t.Stop();
Console.WriteLine(timer.ToString() + ": " + t.Duration);
// Output is: 0.0166666666666667
Seconds
IPerfTimer t = PerfTimerFactory.GetPerfTimer(PerfTimerType.SECONDS);
t.Start();
Thread.Sleep(1000);
t.Stop();
Console.WriteLine(timer.ToString() + ": " + t.Duration);
// Output is: 1
Ticks
IPerfTimer t = PerfTimerFactory.GetPerfTimer(PerfTimerType.TICKS);
t.Start();
Thread.Sleep(1000);
t.Stop();
Console.WriteLine(timer.ToString() + ": " + t.Duration);
// Output is: 1000
Milliseconds
IPerfTimer t = PerfTimerFactory.GetPerfTimer(PerfTimerType.MILLISECONDS);
t.Start();
Thread.Sleep(1000);
t.Stop();
Console.WriteLine(timer.ToString() + ": " + t.Duration);
// Output is: 1000
Hi-Res Milliseconds
IPerfTimer t = PerfTimerFactory.GetPerfTimer(PerfTimerType.HIRESSECONDS);
t.Start();
Thread.Sleep(1000);
t.Stop();
Console.WriteLine(timer.ToString() + ": " + t.Duration);
// Output is: 0.522687052442292
In the above example, the Milliseconds result will always be 1000, since the Thread slept for 1000 seconds. However, this is because rounding is taking place. The Hi-Res result will always vary, since it's the most accurate. For mission-critical timing, always use the PerfTimerType.HIRESSECONDS option.