Win32: Calculate Thread CPU Utilization in a Multi-Core / Multi-Processor System

浪子不回头ぞ 提交于 2019-12-21 17:42:23

问题


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?


回答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

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

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

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.



来源:https://stackoverflow.com/questions/260636/win32-calculate-thread-cpu-utilization-in-a-multi-core-multi-processor-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!