- 追加された行はこの色です。
- 削除された行はこの色です。
#author("2020-01-25T15:02:42+09:00","","")
#author("2020-02-01T17:12:14+09:00","","")
#navi(../)
* CPU使用率を取得するサンプルコード [#ia319a3e]
.NETを使ったCPU使用率を取得するサンプルコードになります。~
CPU''コア単位でCPU使用率を取得''したい場合は、以下のリンク記事を参照ください。~
>''[[CPUコア毎の使用率を取得するサンプルコード>.NET/CPUコア毎の使用率を取得する]]''~
サンプルコードは C#, Visual Basic(VB)を公開しています。
#htmlinsert(windev-top.html)
#contents
* 関連サイト [#w406c12a]
-[[Microsoft | .NET PerformanceCounter クラス>https://docs.microsoft.com/ja-jp/dotnet/api/system.diagnostics.performancecounter]]
* 関連記事 [#md24b2a5]
-[[CPUコア毎の使用率を取得するサンプルコード>.NET/CPUコア毎の使用率を取得する]]
-[[WMIを使って物理メモリ・仮想メモリの使用量等を取得する>.NET/WMIを使って物理メモリ・仮想メモリの使用量等を取得する]]
* 動作確認環境 [#y5a5b256]
-Windows 10 ver.1909
-Visual Studio 2019
-.NET Framework 4.7.2
-コンソールアプリケーション
* CPU使用率取得のサンプルコード [#m0343312]
以下に C#, Visual Basic(VB) によるCPU使用率を取得するサンプルコードを記します。~
約0.5秒ごとにCPU使用率を表示します。
** C# によるCPU使用率取得サンプルコード [#vb1bc900]
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();
}
}
** Visual Basic(VB) によるCPU使用率取得サンプルコード [#r44914bb]
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
** 実行結果 [#zf2619e9]
上記のサンプルコードを実行したときのキャプチャです。
#ref(01.png)
以上、.NETでCPU使用率を取得するサンプルコードの紹介でした。
#htmlinsert(windev-btm.html)