Retrieving Performance Data

Performance counters in Windows NT always increment and are never cleared. The basic mission of a performance monitor in Windows NT is to take a snapshot of the performance counters at the beginning of a time interval, and then take another snapshot at the end of the interval. Find the difference between the values in the first and second snapshots for each counter, and voilą, performance data!

When your custom monitor application is ready to retrieve some performance data, how it does so depends on whether you are monitoring the local computer or a remote computer.

Your first call will open the key for you. To obtain performance data from the local system, use the RegQueryValueEx function, with the HKEY_PERFORMANCE _DATA key. You don't need to open the HKEY_PERFORMANCE_DATA handle or use the RegOpenKey function, but be sure to use RegCloseKey to close the handle when it has finished running. By closing the key when you are finished, you allow the software being monitored to be installed or removed. A software component cannot be installed or removed while it is being monitored. Figure 12.1 shows how Performance Monitor obtains data from the local computer.

Figure 12.1 How Performance Monitor collects performance data

To obtain performance information from a remote system, your monitor should first use the RegConnectRegistry function with the computer name of the remote system and the HKEY_PERFORMANCE_DATA key. This function retrieves a key representing the performance data for the remote system. Then, to retrieve the data, you call RegQueryValueEx using the key you obtained in the RegConnectRegistry call, rather than the HKEY_PERFORMANCE_DATA key.

Figure 12.2 How to obtain performance data

Although you use the register-querying function RegQueryValueEx to collect performance data, the performance data does not come from the Registry database. Instead, calling this function with the appropriate key causes the system to collect the data from the appropriate system object managers. The Registry knows that delegating work to others is a useful skill.

When using the RegQueryValueEx function, your monitor must use the lpcbData parameter to specify a byte count of the amount of data to retrieve. Estimating this amount can be tricky. The amount of data varies between systems because of different configurations, and even different requests on the same system will vary because of differing amounts of system activity (such as the number of current threads).

If a RegQueryValueEx call does not provide enough space, the return value will be ERROR_MORE_DATA. To solve this, your application should include a retry loop in which it passes increasing amounts of buffer space until it no longer gets the error. Then, the application should use the successful buffer size as the starting point for subsequent calls to RegQueryValueEx.