using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace cpu_ctrl { public partial class MainForm : Form { private bool isLoop_cpuCtrl = true; // CPU のコントロールループを継続するかどうか private int timeSpan_cpuCtrl = 100; // CPU のコントロールループの実施間隔 public MainForm() { InitializeComponent(); } delegate void Del_setCPUUsage(float cpuUsage); private void backgroundWorker_CPUCtrl_DoWork(object sender, DoWorkEventArgs e) { // CPU 使用率のチェック用 System.Diagnostics.PerformanceCounter pc_cpu = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total"); // CPU 使用率を設定するためのデリゲート Del_setCPUUsage del_setCPUUsage = cpuUsage => { label_cpu.Text = cpuUsage.ToString("0.0") + " %"; }; while (isLoop_cpuCtrl) { float cpuUsage = pc_cpu.NextValue(); label_cpu.Invoke(del_setCPUUsage, new object[] { cpuUsage }); System.Threading.Thread.Sleep(timeSpan_cpuCtrl); } } private void ToolStripMenuItem_Exit_Click(object sender, EventArgs e) { this.Close(); } private void MainForm_Load(object sender, EventArgs e) { // CPU コントロールスレッドを起動 backgroundWorker_CPUCtrl.RunWorkerAsync(); } private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { // CPU コントロールループを終了する isLoop_cpuCtrl = false; } } }
また、CPU使用率計測のため、起動すると1スレッドが無限ループを実施し、CPUリソースを消費する以下のプログラムも作成しました。(process-dummy)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace process_dummy { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private bool isLoop = true; private void backgroundWorker_dummy_DoWork(object sender, DoWorkEventArgs e) { while (isLoop) ; } private void MainForm_Load(object sender, EventArgs e) { backgroundWorker_dummy.RunWorkerAsync(); } private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { isLoop = false; } } }
この実験結果を以下の動画にまとめました。
実験:CPU使用率の取得
(細かい文字を見るには、解像度を480p以上に設定してください。)
実験に使用したPCは論理プロセッサが8個あります。
process-dummyを1個起動するごとに、PCのCPU使用率の 1/8 を消費します。
process-dummy を 8個起動することで、PCのCPU使用率が 100% になりました。
実験は成功です。