gpt4 book ai didi

windows - CPU 使用率最高的进程的名称

转载 作者:可可西里 更新时间:2023-11-01 13:29:09 25 4
gpt4 key购买 nike

我有一个 Samurize配置显示类似于任务管理器的 CPU 使用图。

如何同时显示当前 CPU 使用率最高的进程的名称?

我希望它最多每秒更新一次。 Samurize 可以调用命令行工具并在屏幕上显示它的输出,因此这也是一个选项。


进一步说明:

我研究过编写自己的命令行 c# .NET 应用程序来枚举从 System.Diagnostics.Process.GetProcesses() 返回的数组,但 Process 实例类似乎不包含 CPU 百分比属性。

我可以用某种方式计算吗?

最佳答案

您想获得它的即时 CPU 使用率(某种)...

实际上,一个进程的即时CPU使用率是不存在的。相反,您必须进行两次测量并计算平均 CPU 使用率,公式非常简单:

AvgCpuUsed = [TotalCPUTime(process,time2) - TotalCPUTime(process,time1)] / [time2-time1]

时间 2 和时间 1 的差异越小,您的测量就越“即时”。 Windows 任务管理器以一秒为间隔计算 CPU 使用率。我发现这已经足够了,您甚至可以考虑每隔 5 秒执行一次,因为测量本身会占用 CPU 周期...

所以,首先,要获得平均 CPU 时间

    using System.Diagnostics;

float GetAverageCPULoad(int procID, DateTme from, DateTime, to)
{
// For the current process
//Process proc = Process.GetCurrentProcess();
// Or for any other process given its id
Process proc = Process.GetProcessById(procID);
System.TimeSpan lifeInterval = (to - from);
// Get the CPU use
float CPULoad = (proc.TotalProcessorTime.TotalMilliseconds / lifeInterval.TotalMilliseconds) * 100;
// You need to take the number of present cores into account
return CPULoad / System.Environment.ProcessorCount;
}

现在,对于“即时”CPU 负载,您需要一个专门的类:

 class ProcLoad
{
// Last time you checked for a process
public Dictionary<int, DateTime> lastCheckedDict = new Dictionary<int, DateTime>();

public float GetCPULoad(int procID)
{
if (lastCheckedDict.ContainsKey(procID))
{
DateTime last = lastCheckedDict[procID];
lastCheckedDict[procID] = DateTime.Now;
return GetAverageCPULoad(procID, last, lastCheckedDict[procID]);
}
else
{
lastCheckedDict.Add(procID, DateTime.Now);
return 0;
}
}
}

对于要监控的每个进程,您应该从计时器(或您喜欢的任何间隔方法)调用该类,如果您希望所有进程都使用Process.GetProcesses静态方法

关于windows - CPU 使用率最高的进程的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51684/

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