How to get CPU utilization with C # real-time

xiaoxiao2021-03-06  50

Using system;

Using system.diagnostics;

Using system.threading;

Public Class CpuloadInfo

{

// Auxiliary Print Methods

Private static void say (String TXT)

{

Console.writeline (TXT);

}

// Auxiliary Print Methods

Private static void Say ()

{

Say ("");

}

// The main method. Command Line Arguments Are Ignored.

[Stathread]

Public static void main ()

{

Say ("$ ID: cpuloadInfo.cs, v 1.2 2002/08/17 17:45:48 RZ65 EXP $");

Say ();

Say ("Attempt to Create a PerformanceCounter Instance:");

Say ("category name =" categoryName);

Say ("Counter Name =" Countername);

Say ("Instance Name =" InstanceName);

PerformanceCounter PC

= New PerformanceCounter (CategoryName, Countername, InstanceName);

"" Performance Counter Was Created. ");

Say ("Property CounterType:" pc.countertype);

Say ();

Say ("Property Counterhelp: pc.counterhelp);

Say ();

"" Entering Measurement Loop. ");

While (True)

{

Thread.sleep (1000); // Wait for 1 SECOND

Float cpuload = pc.nextvalue ();

Say ("CPU LOAD =" CPULOAD "%.");

}

}

// Constants Used to select the Performance Counter.

Private const string categoryName = "processor";

Private const string countername = "% processor time";

Private const string instanceName = "_total";

}

This is the calculation result on my computer:

Entering measurement loop.

CPU LOAD = 0%.

CPU LOAD = 1.941746%.

CPU LOAD = 4.854369%.

CPU LOAD = 10%.

CPU LOAD = 0%.

CPU LOAD = 2.999997%. CPU LOAD = 0.9900987%.

CPU LOAD = 0%.

转载请注明原文地址:https://www.9cbs.com/read-116665.html

New Post(0)