Win32:计算多核/多处理器系统中的线程 CPU 利用率
我目前正在开发一个需要了解 CPU 利用率的 MFC 应用程序。 它可能在不同的时间点有多个线程,但大部分工作是由主线程完成的。
我正在尝试找到一种方法来计算该主线程使用了多少 CPU 百分比。 然而,我遇到了一些问题,如何在多 CPU/多核环境中准确地完成此任务。 问题是大多数系统调用似乎都会提供系统信息,而我需要特定于正在执行主线程的处理器的信息。
我已经研究过 WMI,但它对于这项任务来说似乎有点过分了。 GetThreadTimes() 能满足我的需要吗?
I am currently working on an MFC application that needs to be CPU-utilization aware. It may have multiple threads at different points in time, but the bulk of the work is accomplished by the main thread.
I am trying to find a way to calculate how much percentage of the CPU this main thread utilizes. However, I am running into some problems as to how exactly to accomplish this in a multi-CPU / multi-Core environment. The problem is that most system calls seems to give system information, whereas I need information specific to the processor on which my main thread is executing.
I have looked at WMI, but it seems to be an overkill for the task. Will GetThreadTimes() work for what I need?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的主线程可能在不同的时间在不同的 CPU 上执行,因此“特定于正在执行我的主线程的处理器的信息”可能毫无意义 - 它很可能是所有处理器。 Windows 不会跟踪线程在哪个 CPU 上执行了多少时间,因此您不能询问“给我一个每个 CPU 的该线程的执行时间列表”。 唯一的例外是当您将线程关联掩码设置为单个 CPU 时 - 那么您可以确定,如果线程执行的话,它会在该单个 CPU 上运行。
对于计算运行时,GetThreadTimes 是正确的 API,是的。 如果您想知道进程使用了(理论)CPU 的百分比,请计算
该公式当然假设所有 CPU 具有相同的速度。 如果你想显示线程最近消耗了多少CPU部分,每秒采样一次GetThreadTimes,然后计算
如果你每秒采样一次,现在-上一个大致为1,但你应该记录采样的时间,无论如何 - 系统可能不会让您在采样之间精确睡眠 1 秒。
Your main thread may execute at different CPUs at different times, so "information specific to the processor on which my main thread is executing" might be meaningless - it might well be all processors. Windows doesn't keep track how much time a thread executed on what CPU, so you can't ask "give me a list of execution times for this thread, per CPU". The only exception is when you set a thread affinity mask to a single CPU - then you can be certain that if the thread executes at all, it runs on that single CPU.
For computing run-times, GetThreadTimes is the right API, yes. If you want to what percentage of a (theoretical) CPU the process has used, compute
This formula assumes, of course, that all CPUs have the same speed. If you want to display what CPU portion the thread has recently consumed, sample GetThreadTimes every second, then compute
If you sample every second, now-previous would roughly be 1, but you should record the time of sampling, anyway - the system might not make you sleep exactly 1s between samples.