获取进程的CPU和内存使用情况的正确性能计数器是什么?

Ani*_*jee 64 c# memory-management performancecounter cpu-usage

如何使用.NET 类获取特定进程的CPU内存使用情况PerformanceCounter?还有什么区别

Processor\% Processor TimeProcess\% Processor Time

我对这两者感到有些困惑.

SwD*_*n81 113

这篇文章:

要获得整个PC CPU和内存使用情况:

using System.Diagnostics;
Run Code Online (Sandbox Code Playgroud)

然后全局声明:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Processor", "% Processor Time", "_Total"); 
Run Code Online (Sandbox Code Playgroud)

然后要获得CPU时间,只需调用NextValue()方法:

this.theCPUCounter.NextValue();
Run Code Online (Sandbox Code Playgroud)

这将为您提供CPU使用率

至于内存使用情况,我认为同样适用:

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Memory", "Available MBytes");
Run Code Online (Sandbox Code Playgroud)

然后要获取内存使用情况,只需调用NextValue()方法:

this.theMemCounter.NextValue();
Run Code Online (Sandbox Code Playgroud)

对于特定进程CPU和内存使用情况:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Process", "% Processor Time",              
   Process.GetCurrentProcess().ProcessName);
Run Code Online (Sandbox Code Playgroud)

Process.GetCurrentProcess().ProcessName您希望获取有关信息的进程名称在哪里.

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Process", "Working Set",
   Process.GetCurrentProcess().ProcessName);
Run Code Online (Sandbox Code Playgroud)

Process.GetCurrentProcess().ProcessName您希望获取有关信息的进程名称在哪里.

请注意,工作集本身可能不足以确定进程的内存占用 - 请参阅什么是专用字节,虚拟字节,工作集?

要检索所有类别,请参阅演练:检索类别和计数器

之间的差异Processor\% Processor Time,并Process\% Processor TimeProcessor从PC本身Process是每个个体的过程.因此,处理器的处理器时间将在PC上使用.进程的处理器时间将是指定的进程使用情况.有关类别名称的完整说明:性能监视器计数器

使用性能计数器的替代方法

使用System.Diagnostics.Process.TotalProcessorTimeSystem.Diagnostics.ProcessThread.TotalProcessorTime属性来计算您的处理器使用情况,如本文所述.

  • @Legend我的粗略测试显示它是每个处理器的处理器使用量之和.对于4个内核,`PerformanceCounter("Process","%Processor Time",Process.GetCurrentProcess().ProcessName)`可以返回到"400",这意味着该进程正在使用每个CPU的100%.为什么这个不明确*任何地方*都是不幸的,因为不得不依靠粗略的测试.这是"我如何获得进程的CPU使用率?"的最高投票/回答问题.对于c#,仍然没有人提到它.各种technet,msdn和msdn博客帖子都有相互矛盾的信息,只是为了让它更加混乱. (7认同)
  • 对于仍然在这里登陆的任何人,我想附上@Quantic 关于计数器值的说法。详细 [此处](https://social.technet.microsoft.com/wiki/contents/articles/12984.understanding-processor-processor-time-and-process-processor-time.aspx),`处理器 (% Processor Time)` 计数器将超过 100,并将提供计算机中所有处理器/内核/等的总使用量。但是,“处理器(% 处理时间)”按逻辑处理器的数量进行缩放。要获得计算机的平均使用率,请将结果除以 `Environment.ProcessorCount` (4认同)
  • 如果我按照上面的方式创建 CPUCounter,则会收到 InvalidOPerationException:“无法加载计数器名称数据,因为从注册表中读取了无效索引 ''。” (2认同)
  • 感谢您的详细回答!当调用`new PerformanceCounter(“ Process”,“%Processor Time”,Process.GetCurrentProcess()。ProcessName);`时,我得到一个百分比。我应该如何解释这个百分比?这是机器上所有内核的百分比吗? (2认同)