c#实时获取cpu占有率
时间: 2023-10-08 21:04:32 浏览: 126
您可以使用C#中的`PerformanceCounter`类来实时获取CPU占用率。以下是一个简单的示例代码:
```csharp
using System.Diagnostics;
namespace GetCPUUsage
{
class Program
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
while (true)
{
float cpuUsage = cpuCounter.NextValue();
Console.WriteLine("CPU Usage: " + cpuUsage + " %");
Thread.Sleep(1000);
}
}
}
}
```
该代码将每秒输出CPU的占用率。您可以通过修改`Thread.Sleep()`的参数来调整输出频率。
相关问题
c#怎么实时获取当前cpu占用率
你可以使用 `PerformanceCounter` 类来实时获取当前 CPU 的占用率。以下是一个示例代码:
```csharp
using System.Diagnostics;
// 创建一个 PerformanceCounter 对象
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
while (true)
{
// 获取当前 CPU 占用率
float cpuUsage = cpuCounter.NextValue();
Console.WriteLine($"当前 CPU 占用率:{cpuUsage}%");
// 等待 1 秒
Thread.Sleep(1000);
}
```
这段代码将会每秒输出一次当前 CPU 占用率,并且会一直运行下去。需要注意的是,`PerformanceCounter` 对象的构造函数中的参数 `"Processor"` 表示监控的是 CPU 的性能计数器,`"% Processor Time"` 表示监控的是 CPU 的占用率,`"_Total"` 表示监控的是所有 CPU 的总占用率。
c#获取cpu使用率
你可以使用 System.Diagnostics 命名空间下的 PerformanceCounter 类来获取 CPU 使用率。以下是一个示例代码:
```
using System.Diagnostics;
...
// 创建一个 PerformanceCounter 对象
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
// 获取 CPU 使用率
float cpuUsage = cpuCounter.NextValue();
// 等待一段时间,然后再次获取 CPU 使用率
System.Threading.Thread.Sleep(1000);
cpuUsage = cpuCounter.NextValue();
```
在上面的代码中,我们首先创建了一个 PerformanceCounter 对象,指定了计数器的类别为 "Processor",计数器名称为 "% Processor Time",实例名称为 "_Total",这样就可以获取整个系统的 CPU 使用率。然后我们通过调用 NextValue 方法来获取 CPU 使用率的值。由于 CPU 使用率是实时变化的,因此我们在获取完一次值后等待一段时间再次获取,这样可以得到更准确的结果。