ASP.NET CORE LINUX 获取 CPU 使用情况

Car*_*ter 6 asp.net-core

使用此代码,这适用于 Windows。对于 Linux(Ubuntu)“Linux 中未提供 PerformanceCounter”

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

在 Linux 中,如何通过 ID 调用此方法来获取进程的 CPU 使用率?

小智 8

PerformanceCounter 代表 Windows NT 性能计数器组件,这意味着它只能在 Windows 上运行并侦听 Windows 性能监视器。

对于Linux,您应该使用System.Diagnostics.Process.GetCurrentProcess()来计算 CPU 使用率。例子:

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

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

// Stop watching to mensure
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;
Run Code Online (Sandbox Code Playgroud)

  • 您知道如何获取总体 CPU 使用率(而不是特定进程)吗? (5认同)