ASP.NET CORE LINUX Get CPU USAGE

Viewed 3457

With this code, this works for windows. For Linux(Ubuntu) "PerformanceCounter is not provided in Linux"

PerformanceCounter counter = GetPerfCounterForProcessId(process.Id); //Just gets process by id dont worry...
var processUsages = counter.NextValue();
double processUsage = counter.NextValue() / Environment.ProcessorCount;

How could I transfer this method to get the CPU Usage from a process by ID with it working in Linux?

1 Answers

PerformanceCounter represents a Windows NT performance counter component that means it only works on Windows and listen on Windows Performance Monitor.

For Linux, you should use the System.Diagnostics.Process.GetCurrentProcess() to calculate CPU Usage. Example:

var startTime = DateTime.UtcNow;
var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
var stopWatch = new Stopwatch();
// Start watching CPU
stopWatch.Start();

// Meansure something else, such as .Net Core Middleware
await _next.Invoke(httpContext);

// Stop watching to meansure
stopWatch.Stop();
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);

var cpuUsagePercentage = cpuUsageTotal * 100;
Related