安裝套件
在 .NET Core (.NET 5+)需要安裝 System.Diagnostics.PerformanceCounter 套件,使用 .NET CLI 執行以下指令安裝:
dotnet add package System.Diagnostics.PerformanceCounter
讀取 CPU 總使用率
using System.Diagnostics;
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
_ = cpuCounter.NextValue(); // 第一次讀取的資料是 0 ,之後統計值才會正確,所以先讀取一次
while (true)
{
Thread.Sleep(1000);
// 讀取 CPU 使用率
float cpuUsage = cpuCounter.NextValue();
// 輸出 CPU 使用率
Console.WriteLine($"Current CPU Usage: {cpuUsage}%");
// Current CPU Usage: 12.502403%
}
讀取各 CPU 核心使用率
using System.Diagnostics;
int coreCount = Environment.ProcessorCount; // 取得 CPU 核心數
PerformanceCounter[] cpuCounters = new PerformanceCounter[coreCount];
for (int i = 0; i < coreCount; i++)
{
cpuCounters[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
_ = cpuCounters[i].NextValue();
}
while (true)
{
Thread.Sleep(1000);
for (int i = 0; i < coreCount; i++)
{
float cpuUsage1 = cpuCounters[i].NextValue();
Console.WriteLine($"CPU Core {i} Usage: {cpuUsage1}%");
// CPU Core 3 Usage: 4.697951%
}
}
註: 上面的程式碼只在 Windows 平台有效
參考資料:
Microsoft.Learn - PerformanceCounter Class
感謝教學~
回覆刪除