Is there anything better than GetThreadTimes for obtaining per-thread CPU usage information?

A customer was using the Get­Thread­Times function for high-resolution profiling of performance-sensitive code, but found that its accuracy is rather poor. They were hoping there would be something more along the lines of a Query­Performance­Counter that reported only CPU time consumed by a particular thread, rather than by the system in general.

Fortunately, there is. The Query­Thread­Cycle­Time function gives you the CPU cycles consumed by a particular thread. This includes time spent both in user mode and in kernel mode.

Note, however, that these values are reported directly from the CPU using mechanisms like RDTSC or the performance monitor control register. This means that the actual results are at the mercy of whatever the CPU manufacturer decides the CPU cycle counter means. Maybe they correspond to wall clock time; maybe they don't.

Comments (7)
  1. ZLB says:

    Would this behaviour also include the possibility of warping backwards and forwards on multiple CPU system or does the kernel tot up the time before/after scheduling?

    1. alegr1 says:

      It’s very easy, as long as the cycle counter runs with constant speed on all CPUs.
      When the scheduler switches to a thread, the CPU cycle counter is saved in the thread context. When the thread loses CPU (even for interrupts and DPCs), the saved count is subtracted from the current and added to the thread’s total. The counters on different CPUs can be all around the place and still the total count will be accurate.

  2. otstrel says:

    Funny coincidence, I’ve been looking into the very same problem earlier today and found another bit of information that may be useful:

    1. But probabilistically, if your thread consumes only 1% of its quantum, then 1 out of every 100 timer ticks will happen to hit while the thread is running. In your example, the calculation thread kept releasing its quantum, so it wasn’t actually running the whole time.

      1. jake says:

        raymond debugs windows. raymond blogs. raymond debugs blogs!

        1. Ray Koopa says:

          Raymond blocks windows? Are the zombies outside?

  3. Joshua A. Schaeffer says:

    Is it considered more acceptable to calculate CPU %usage by cycles or by wall clock time? Or does it not matter?

Comments are closed.

Skip to main content