このエントリーをはてなブックマークに追加


CPU使用率を取得するサンプルコード

.NETを使ったCPU使用率を取得するサンプルコードになります。
CPUコア単位でCPU使用率を取得したい場合は、以下のリンク記事を参照ください。

CPUコア毎の使用率を取得するサンプルコード

サンプルコードは C#, Visual Basic(VB)を公開しています。

関連サイト

関連記事

動作確認環境

  • Windows 10 ver.1909
  • Visual Studio 2019
  • .NET Framework 4.7.2
  • コンソールアプリケーション

CPU使用率取得のサンプルコード

以下に C#, Visual Basic(VB) によるCPU使用率を取得するサンプルコードを記します。
約0.5秒ごとにCPU使用率を表示します。

C# による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();
    }
}

Visual Basic(VB) によるCPU使用率取得サンプルコード

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

実行結果

上記のサンプルコードを実行したときのキャプチャです。

01.png

以上、.NETでCPU使用率を取得するサンプルコードの紹介でした。


添付ファイル: file01.png 336件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2020-02-01 (土) 17:12:14