糯米文學吧

位置:首頁 > 計算機 > 計算機硬件

利用C#監控計算機CPU的使用率

今天在網上看到一段比較好玩的代碼,用來顯示本地計算機CPU的使用情況,整理如下,歡迎使用,更多信息請瀏覽應屆畢業生考試網!

利用C#監控計算機CPU的使用率

using System;

using nostics;

using ading;

namespace ConsoleApplication1

{

class Program

{

private const string CategoryName = "Processor";

private const string CounterName = "% Processor Time";

private const string InstanceName = "_Total";

private static void OutPut(string txt)

{

eLine(txt);

}

[STAThread]

public static void Main()

{

PerformanceCounter pc = new PerformanceCounter(CategoryName, CounterName, InstanceName);

OutPut("----------------------------開始創造性能計數器----------------------------");

OutPut("計數器類型:" + terType);

OutPut("計數器的`説明:" + terHelp);

OutPut("開始輸出:");

while (true)

{

p(1000);

float cpuLoad = Value();

OutPut("CPU 耗用:" + cpuLoad + "%");

}

}

}

}

直接運行程序,對比控制枱輸出的結果與計算機的Windows任務管理器中顯示的CPU使用值,會發現原來Windows任務管理器顯示的值是CPU使用率的四捨五入的結果。有興趣的朋友可以自己複製代碼試試看啦。