来自this 发帖:
获取整个 PC CPU 和内存使用情况:
using System.Diagnostics;
然后全局声明:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
然后要获取CPU时间,只需调用NextValue()方法:
this.theCPUCounter.NextValue();
这将为您提供 CPU 使用率
至于内存使用,我相信同样适用:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
然后要获取内存使用情况,只需调用NextValue()方法:
this.theMemCounter.NextValue();
对于特定进程的 CPU 和内存使用情况:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
Process.GetCurrentProcess().ProcessName 是您希望获取相关信息的进程名称。
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
其中Process.GetCurrentProcess().ProcessName 是您希望获取有关信息的进程名称。
请注意,工作集本身可能不足以确定进程的内存占用——请参阅What is private bytes, virtual bytes, working set?
要检索所有类别,请参阅Walkthrough: Retrieving Categories and Counters
Processor\% Processor Time 和 Process\% Processor Time 之间的区别在于,Processor 来自 PC 本身,Process 来自各个进程。所以处理器的处理器时间将是PC上的使用。进程的处理器时间将是指定的进程使用情况。类别名称的完整描述:Performance Monitor Counters
使用性能计数器的替代方法
使用System.Diagnostics.Process.TotalProcessorTime 和System.Diagnostics.ProcessThread.TotalProcessorTime 属性来计算您的处理器使用率,正如article 所描述的那样。