In this article I will share a way of getting the CPU usage % of a .NET core app. This matches up with the value reported in task manager.
In full .NET framework, most people used thePerformanceCounter
class to work this out like so:
private async Task<int> GetCpuUsageForProcess()
{
var currentProcessName = Process.GetCurrentProcess().ProcessName;
var cpuCounter = new PerformanceCounter("Process", "% Processor Time", currentProcessName); cpuCounter.NextValue(); await Task.Delay(500); return (int)cpuCounter.NextValue();
}
The PerformanceCounter
class isn’t available in .NET Core though so another approach has to be used.
This involves using the Process
class from System.Diagnostics
and the TotalProcessorTime
property along with a delay in time. It is then possible to figure out how much processor time has been consumed from the process and hence get the percentage:
private async Task<double> GetCpuUsageForProcess()
{
var startTime = DateTime.UtcNow;
var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime; await Task.Delay(500);
var endTime = DateTime.UtcNow;
var endCpuUsage = Process.GetCurrentProcess().TotalProcessorTime; var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
var totalMsPassed = (endTime - startTime).TotalMilliseconds; var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed); return cpuUsageTotal * 100;
}
An example of how this can be used can be found on my github at https://github.com/jackowild/CpuUsagePercentageDotNetCoreExample
It outputs the CPU usage % every 2 seconds: