性能计数器按进程ID而不是名称?

时间:2012-02-02 15:56:22

标签: c# performancecounter

我正在跟踪同一个应用程序的多个实例,需要获取两个进程的内存和CPU使用情况。但是,我似乎无法找到一种方法来使用性能计数器,并知道哪个结果是针对哪个进程的。我已经看到我可以将#1等附加到名称的末尾以获得每个的结果,但这并不能告诉我哪个是哪个进程。

如何确定ProcessId或将进程ID传递给计数器以获得具有相同名称的每个进程的结果?

PerformanceCounterCPU.CategoryName = "Process";
PerformanceCounterCPU.CounterName = "% Processor Time";
PerformanceCounterCPU.InstanceName = proc.ProcessHandle.ProcessName;

PerformanceCounterMemory.CategoryName = "Process";
PerformanceCounterMemory.CounterName = "Working Set - Private";
PerformanceCounterMemory.InstanceName = proc.ProcessHandle.ProcessName;

2 个答案:

答案 0 :(得分:30)

This answer相关问题可能会有效:

private static string GetProcessInstanceName(int pid)
{
  PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");

  string[] instances = cat.GetInstanceNames();
  foreach (string instance in instances)
  {

     using (PerformanceCounter cnt = new PerformanceCounter("Process",  
          "ID Process", instance, true))
     {
        int val = (int) cnt.RawValue;
        if (val == pid)
        {
           return instance;
        }
     }
  }
  throw new Exception("Could not find performance counter " + 
      "instance name for current process. This is truly strange ...");
}

答案 1 :(得分:1)

如果您不介意机器范围的注册表更改,您可以configure Windows to use the form ProcessName_ProcessID for Perf Counter instance names,而不是附加#1,#2等:

创建DWORD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance\ProcessNameFormat并将其值设置为2。

如果您坚持使用#1,#2等形式,请注意the instance name for a given process can change during the process' lifetime