Microsoft KB Archive/262938

{|
 * width="100%"|

HOWTO: Get % Processor Time Correctly By Using the Performance Data Helper (PDH) API

 * }

Q262938

-

The information in this article applies to:


 * Microsoft Win32 Application Programming Interface (API), included with:
 * the operating system: Microsoft Windows 2000
 * Microsoft Windows NT Server version 4.0
 * Microsoft Windows NT Workstation version 4.0

-

SUMMARY
Performance Data Helper (PDH) functions can be used to retrieve performance data. This article explains how an application can obtain the % (percent) Processor Time correctly, based on the underlying calculation performed by the PDH library.

MORE INFORMATION
The % Processor Time performance counter is the percentage of time that the processor is running a non-Idle thread. This counter is designed as a primary indicator of processor activity. It is calculated by measuring the time that the processor spends running the thread of the Idle process in each sample interval, and subtracting that value from 100 percent. Each processor has an Idle thread, which consumes cycles when no other threads are ready to run. It can be viewed as the fraction of the time that is spent doing useful work. The calculation for this performance counter is performed as follows.

Counter Type: PERF_100NSEC_TIMER_INV

PERF_100NSEC_TIMER_INV - The inverse of the timer. Used when the object is not in use.

When the application calls the PdhCollectQueryData PDH function the first time, the PDH library collects X0 (the total time taken by the processor that is running the thread of the idle process) and Y0 (the time measured in Time base units). The second time the application calls PdhCollectQueryData, the previous sample becomes X0 and Y0, and the current call becomes X1 and Y1.

When the application calls the PdhGetFormattedCounterValue PDH function, the calculation described in the previous paragraph is performed to calculate the % Processor Time. This calculation relies on a previous sample, which is not present if PdhCollectQueryData is called only once (there is no X0 and Y0). Therefore, if any performance counter requires two sample collections, PdhGetFormattedCounterValue can be called only after the second PdhCollectQueryData is called.

Furthermore, when retrieving the % Processor Time, there must be a delay between sample collections, because just running the code will have a slight impact on the calculation of % Processor Time. The application can delay by calling Sleep(few 100 milliseconds) in between PdhCollectQueryData function calls.

Additional query words:

Keywords : kbAPI kbKernBase kbPerfMon kbSDKWin32 kbDSupport kbGrpDSKernBase

Issue type : kbhowto

Technology : kbAudDeveloper kbWin32sSearch kbWin32API