Win32:计算多核/多处理器系统中的线程CPU利用率 [英] Win32: Calculate Thread CPU Utilization in a Multi-Core / Multi-Processor System

查看:79
本文介绍了Win32:计算多核/多处理器系统中的线程CPU利用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用需要了解CPU使用率的MFC应用程序.它可能在不同的时间点具有多个线程,但是大部分工作是由主线程完成的.

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.

我正在尝试找到一种方法来计算此主线程使用的CPU百分比.但是,我在如何在多CPU/多核环境中准确实现这一目标方面遇到了一些问题.问题在于大多数系统调用似乎都提供系统信息,而我需要特定于我主线程正在其上执行的处理器的信息.

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.

我已经看过WMI,但这似乎对完成这项任务有些过分. GetThreadTimes()是否可以满足我的需要?

I have looked at WMI, but it seems to be an overkill for the task. Will GetThreadTimes() work for what I need?

推荐答案

您的主线程可能在不同的时间在不同的CPU上执行,因此特定于我的主线程正在执行的处理器的信息"可能没有意义-可能最好是所有处理器. Windows不会跟踪线程在哪个CPU上执行多少时间,因此您无法询问给我每个CPU该线程的执行时间列表".唯一的例外是当您将线程相似性掩码设置为单个CPU时-您可以确定,如果线程完全执行,那么它将在该单个CPU上运行.

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.

对于计算运行时,GetThreadTimes是正确的API,是的.如果您希望进程使用多少(理论上)的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

(kerneltime+usertime) / (now - starttime) / numberofcpus

当然,此公式假定所有CPU都具有相同的速度.如果要显示线程最近消耗的CPU部分,请每秒采样GetThreadTimes,然后进行计算

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

(usedtimenow - usedtimeprevious) / (now - previous) / numberofcpus

如果您每秒进行一次采样,则现在的前一个大约为1,但是无论如何,您都应该记录采样时间-系统可能不会让您在两次采样之间精确地睡1s.

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.

这篇关于Win32:计算多核/多处理器系统中的线程CPU利用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆