如何获取多处理器/多核系统上进程的准确 CPU 使用率
或者也许这个问题更像是“我在这里公然做错了什么?”
我有一个测试应用程序,它除了观察自己的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你是对的 - 你必须将性能计数器的数字除以 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.