gpt4 book ai didi

.net - 如何在多处理器/多核系统上获得进程的准确 CPU 使用率

转载 作者:行者123 更新时间:2023-12-03 17:58:57 26 4
gpt4 key购买 nike

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

我有一个测试应用程序,它只观察自己的 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。我假设它与多核和超线程有关。我该怎么做才能获得我正在寻找的实际值(value)? (此特定进程的总处理器时间百分比)

最佳答案

您是正确的 - 您必须将性能计数器的数量除以 CPU 数量乘以每个 CPU 的实际线程数量 - 每个内核一个,如果超线程是一个因素,则每个内核加上一个。

在 C# 中,我不知道如何确定这一点。在 native 代码中,您可以使用 GetLogicalProcessorInformationits associated structure计算逻辑处理器,包括共享内核的处理器。

关于.net - 如何在多处理器/多核系统上获得进程的准确 CPU 使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5955752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com