首页 > 开发 > 综合 > 正文

如何用C#实时获取CPU利用率

2024-07-21 02:20:28
字体:
来源:转载
供稿:网友
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);
say("performance counter was created.");
say("property countertype: " + pc.countertype);
say();

say("property counterhelp: " + pc.counterhelp);
say();
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";
}

这是在我计算机上的计算结果:
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 %.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表