是否有任何命令或可能的方法来了解Windows操作系统中的cpu利用率,以便在命令行或批处理脚本中使用?
我一直试图在C#中获得Windows PC(Windows 7运行.Net 4.5)的总CPU使用率.看起来使用PerformanceCounter应该能够满足我的需求.
我根据以下三个链接编写了一些试用代码(并检查了msdn页面),这是最基本的版本:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace EntropyProject
{
class Program
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
while(true)
{
try
{
float firstValue = cpuCounter.NextValue();
System.Threading.Thread.Sleep(500);
Console.WriteLine("Before getting processor:");
float currentCpuUsage = cpuCounter.NextValue();
Console.WriteLine("After getting processor:");
System.Threading.Thread.Sleep(1000);
Console.WriteLine(currentCpuUsage);
}
catch (Exception e)
{
Console.WriteLine("\n{0}\n", e.Message);
}
System.Threading.Thread.Sleep(10000);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
每当调用NextValue时,都会触发下面的异常错误.这似乎是性能计数器值出现问题的常见问题. …