取多核CPU使用率
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
PerformanceCounter[] counters = new PerformanceCounter[System.Environment.ProcessorCount];
for (int i = 0; i < counters.Length; i++)
{
counters[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
}
float fCpuRatio = 0;
for (int i = 0; i < counters.Length; i++)
{
float f = counters[i].NextValue();
fCpuRatio = fCpuRatio + f;
}
fCpuRatio = fCpuRatio / 2;
Console.WriteLine("CPU USAGE:{0:D}", (int)fCpuRatio);
}
}
以上是我修改后的代码,我要生成一个获取多核cpu使用率的exe文件供其他人调用。但是我发现这个程序运行后每次取到的使用率都是“0”啊。
这是我从网上找到的源码:
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
PerformanceCounter[] counters = new PerformanceCounter[ System.Environment.ProcessorCount ];
for(int i=0; i<counters.Length; i++)
{
counters[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
}
while(true)
{
for(int i=0; i<counters.Length; i++)
{
float f = counters[i].NextValue();
Console.WriteLine("CPU-{0}: {1:f}%", i, f);
}
Console.WriteLine();
System.Threading.Thread.Sleep(1000);
}
}
}
这个运行是没有问题的
[解决办法]
该回复于2010-06-21 13:14:57被版主删除