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


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?

Best Solution

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.