c#获取系统cpu占用
时间: 2023-11-18 21:08:04 浏览: 35
你可以使用 System.Diagnostics 命名空间下的 PerformanceCounter 类来获取系统 CPU 占用率。以下是一个示例代码:
```csharp
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
while (true)
{
Console.WriteLine($"CPU占用率: {cpuCounter.NextValue()}%");
System.Threading.Thread.Sleep(1000);
}
}
}
```
上述代码将每秒输出一次 CPU 占用率。你可以修改输出方式,以适应你的具体需求。
相关问题
C# 准确获取系统 CPU 使用率
可以借助 System.Diagnostics 命名空间下的 PerformanceCounter 类来获取系统 CPU 使用率。具体步骤如下:
1. 引入 System.Diagnostics 命名空间:
```
using System.Diagnostics;
```
2. 创建 PerformanceCounter 对象:
```
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
```
其中,第一个参数 "Processor" 表示 CPU 监视器,第二个参数 "% Processor Time" 表示 CPU 使用率,第三个参数 "_Total" 表示所有 CPU 核心的总体使用率。
3. 调用 NextValue 方法获取 CPU 使用率:
```
float cpuUsage = cpuCounter.NextValue();
```
注意,第一次调用 NextValue 方法获取的是 0,因为需要先获取一次初始值,之后才能获取正确的 CPU 使用率。
完整示例代码如下:
```
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
// 获取初始值
cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
// 获取 CPU 使用率
float cpuUsage = cpuCounter.NextValue();
Console.WriteLine("CPU 使用率:{0}%", cpuUsage);
}
}
```
C# 获取系统内存和CPU使用率
获取系统内存使用率可以使用`PerformanceCounter`类,具体代码如下:
```csharp
using System.Diagnostics;
// 获取系统内存使用率
public float GetMemoryUsage()
{
PerformanceCounter memCounter = new PerformanceCounter("Memory", "Available MBytes");
return 100 - (memCounter.NextValue() / new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory) * 100;
}
```
获取系统CPU使用率可以使用`PerformanceCounter`类,具体代码如下:
```csharp
using System.Diagnostics;
// 获取系统CPU使用率
public float GetCpuUsage()
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
return cpuCounter.NextValue();
}
```
注意,在使用`PerformanceCounter`类时需要在程序的引用中添加`System.Diagnostics`和`Microsoft.VisualBasic`两个命名空间。