C#でCPU使用率を取得する

C#で実行中PCのCPU使用率を取得しようとした場合、下記の様なコードで取れる、と思われます。System.Diagnostics 名前空間を using しておいてください。

パフォーマンスカウンタから値を取得するhttp://dobon.net/vb/dotnet/system/readperformancecounter.html

PerformanceCounter pfcounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
float cpu = pfcounter.NextValue();

……が、なぜか0しか取得出来ない。

MSDNやGoogleに頼ってみてもなかなか明確な答えが見つけられなかったものの、
どうも「最初の1回目の値は使えない」「すぐには値が取れない」らしい。

いろいろ試した結果、以下がCPU使用率を正常に取得できたコードです。
Visual Studio Express 2013 for Windows Desktop + .netFramework 4.5で動作確認済み。

PerformanceCounter pfcounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
float cpu = pfcounter.NextValue();
Thread.Sleep(1000);
cpu = pfcounter.NextValue();

とりあえず動いた、という大変アレなコードですが忘備録として。
(PerformanceCounter インスタンスの nextValue() の計算方法は PerformanceCounterType 列挙体によってが制御されているので、その辺りが関係ありそう? )

Share this…