.NETを使ったCPU使用率を取得するサンプルコードになります。
CPUコア単位でCPU使用率を取得したい場合は、以下のリンク記事を参照ください。
サンプルコードは C#, Visual Basic(VB)を公開しています。
以下に C#, Visual Basic(VB) によるCPU使用率を取得するサンプルコードを記します。
約0.5秒ごとにCPU使用率を表示します。
using System;
using System.Diagnostics;
using System.Threading;
class CpuUsage
{
private PerformanceCounter cpuCounter;
static void Main(string[] args)
{
CpuUsage cpuUsage = new CpuUsage();
cpuUsage.cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
while(true)
{
Console.WriteLine("CPU : {0:f}%", cpuUsage.GetCpuUsage(cpuUsage.cpuCounter));
Thread.Sleep(500);
}
}
private float GetCpuUsage(PerformanceCounter pc)
{
return pc.NextValue();
}
}
Imports System.Threading
Module Module1
Sub Main()
Dim cpuCounter As PerformanceCounter
cpuCounter = New PerformanceCounter("Processor", "% Processor Time", "_Total")
While True
Console.WriteLine("CPU : {0:f}%", GetCpuUsage(cpuCounter))
Thread.Sleep(500)
End While
End Sub
Private Function GetCpuUsage(ByVal pc As PerformanceCounter) As Single
Return pc.NextValue()
End Function
End Module
上記のサンプルコードを実行したときのキャプチャです。
以上、.NETでCPU使用率を取得するサンプルコードの紹介でした。