如何获取多处理器/多核系统上进程的准确 CPU 使用率

发布于 2024-11-06 20:13:29 字数 863 浏览 0 评论 0原文

或者也许这个问题更像是“我在这里公然做错了什么?”

我有一个测试应用程序,它除了观察自己的 CPU 使用情况外什么也不做。它看起来有点像这样:

protected PerformanceTrace()
{
   Process currentProcess = Process.GetCurrentProcess();
   this.cpuCounter = new PerformanceCounter("Process", "% Processor Time", currentProcess.ProcessName);
   this.coreCount = Environment.ProcessorCount;
}

private int coreCount;
private DateTime lastCpuRead = DateTime.MinValue;
private float _cpuUsage;
private float CpuUsage
{
   get
   {
      if ((DateTime.Now - this.lastCpuRead) > TimeSpan.FromSeconds(1.0))
      {
         this._cpuUsage = this.cpuCounter.NextValue();
      }
      return this._cpuUsage / this.coreCount;
   }
}

CpuUsage 属性的读取非常频繁。事情是这样的:

在我的机器上,Environment.ProcessorCount 生成的值为 2。但是,来自计数器的值通常高达 800。我假设它与多个有关核心和超线程。我该怎么做才能获得我正在寻找的实际价值? (此特定进程的总处理器时间百分比)

Or maybe the question is more like "What am I doing blatantly wrong here?"

I have a test app which does nothing but watch its own cpu usage. It looks a little something like this:

protected PerformanceTrace()
{
   Process currentProcess = Process.GetCurrentProcess();
   this.cpuCounter = new PerformanceCounter("Process", "% Processor Time", currentProcess.ProcessName);
   this.coreCount = Environment.ProcessorCount;
}

private int coreCount;
private DateTime lastCpuRead = DateTime.MinValue;
private float _cpuUsage;
private float CpuUsage
{
   get
   {
      if ((DateTime.Now - this.lastCpuRead) > TimeSpan.FromSeconds(1.0))
      {
         this._cpuUsage = this.cpuCounter.NextValue();
      }
      return this._cpuUsage / this.coreCount;
   }
}

The CpuUsage property is read very frequently. Here's the thing:

On my machine, Environment.ProcessorCount produces a value of 2. However, the value coming from the counter is often up to 800. What I am assuming is it has something to do with multiple cores and hyperthreading. What can I do to get the actual value that I'm looking for? (The total % processor time for this particular process)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

指尖上的星空 2024-11-13 20:13:29

你是对的 - 你必须将性能计数器的数字除以 CPU 数量乘以每个 CPU 的实际线程数 - 每个核心一个,加上每个核心一个(如果超线程是一个因素)。

在 C# 中我不知道如何确定这一点。在本机代码中,您可以使用 GetLogicalProcessorInformation其关联结构用于对逻辑处理器进行计数,包括共享核心的逻辑处理器。

You are rigt - you have to divide the number from Performance Counters by the number of CPUs times the number of real threads per CPU - one per core, plus one per core if hyperthreading is a factor.

In C# I don't know how to determine this. In native code you can use GetLogicalProcessorInformation and its associated structure to count the logical processors, including those that share a core.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文