您的位置:首页 > 其它

编写程序 控制cpu占用率-3

2011-10-12 19:22 274 查看
上一节讲了通过GetTickCount()控制时间片的切换,然而MS .NET FRAMEWORK还提供了PerformanceCounter这一对象,可以获得系统资源的各种性能数据,通过这个PerformanceCounter 对象,我们可以更准确的获得CPU的信息。

上一节连接:

http://blog.csdn.net/weixingstudio/article/details/6867373

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace cpu_3_csharp
{
class Program
{
static void Main(string[] args)
{
float level=150F;
PerformanceCounterCategory[] test = PerformanceCounterCategory.GetCategories();
for (int i = 0; i < test.Length; i++)
{
//Console.WriteLine(test[i].CategoryName);
if (test[i].CategoryName == "Processor")
{
string[] temp = test[i].GetInstanceNames();
//Console.WriteLine(temp.Length);
for (int j = 0; j < temp.Length; j++)
{
Console.WriteLine(test[i].MachineName);
Console.WriteLine("------------------------");
Console.WriteLine(temp[j]);
Console.WriteLine("------------------------");

PerformanceCounter[] counters = test[i].GetCounters(temp[j]);
for (int k = 0; k < counters.Length; k++)
{
Console.WriteLine(counters[k].CounterName);
}
}
}
}

Console.WriteLine("*******************************************************");

PerformanceCounter p = new PerformanceCounter("Processor","% Processor Time","_Total");
Console.WriteLine(p.NextValue());
while (true)
{
//Console.WriteLine(p.NextValue());
if (p.NextValue() > level)
{
System.Threading.Thread.Sleep(10);
}
}
}
}
}


在 Console.WriteLine("*******************************************************"); 语句前的操作暂时不用管,因为我是测试用的。

通过设定一个level值,当CPU的使用率超过这个值以后让其休眠,否则进行不停的空循环。

 

但是结果并不是理想,因为同样像上一节那样出现了一个内核繁忙一个内核空闲的现象,稍后将解决双核处理器的问题。



 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string float class .net 测试