Introduction to Windows performance counters in VC

Source: Internet
Author: User

Introduction to Windows performance counters in VC

Author: wlzqin

Download source code

Preface
Microsoft windwos NT/2000 provides a powerful API set to access numerous counters of system events and performance data. We can get the counter value in real time or read the counter data from a log file. Powerful and easy to use. Next I will briefly talk about how to use Windows performance counters in VC. Let's get started.
A simple example is used to describe how to use performance counters. For example, how do we obtain the CPU usage of a running process? You must say, "This is not simple, there are many methods ". Of course, I admit it is not hard, and there are indeed many methods. But which method is the simplest? What is the highest efficiency? I guess the performance counter is used.

The basic steps for using performance counters are:

  1. Open the counter pdhopenquery;
  2. Allocate space for counter handles;
  3. Add the counters you are interested in to pdhaddcounter;
  4. Collect data pdhcollectquerydata;
  5. Obtain the counter value pdhgetformattedcountervalue;
  6. Disable the pdhclosequery counter;

The steps are as follows:

Step 1:
In the header file

#include <"Pdh.h">

In the implementation file,

#pragma comment ( lib , "Pdh.lib" )

Step 2: Open the counter and allocate space to the counter handle

Hqueryhquery = NULL; pdh_status pdhstatus; hcounter * pcounterhandle = NULL ;__ try {// open the counter pdhstatus = pdhopenquery (0, 0, & hquery); If (pdhstatus! = Error_success) {__ leave;} pcounterhandle = (hcounter *) globalalloc (gptr, sizeof (hcounter); If (pcounterhandle = NULL) {__ leave ;}} __finally {If (abnormaltermination ()){}}

Step 3: Create a counter (assuming you want to obtain the CPU usage of the QQ Program)

Pdh_fmt_countervaluefmtvalue; dworddwctrtype ;__ try {pdhstatus = pdhaddcounter (hquery, _ text ("process (_ text (" QQ ") // % processor time"), 0, pcounterhandle ); if (pdhstatus! = Error_success) {__ leave;} pdhstatus = pdhcollectquerydata (hquery); If (pdhstatus! = Error_success) {__ leave;} // obtain the current counter value pdhstatus = pdhgetformattedcountervalue (* pcounterhandle, pdh_fmt_double, & dwctrtype, & fmtvalue); If (pdhstatus! = Error_success) {__ leave;} // fmtvalue. doublevalue is the CPU usage of the program at this moment (real-time data can be obtained through cyclic calls) }__ finally {If (abnormaltermination ()){}}

Step 4: Close the counter

Pdhstatus = pdhclosequery (hquery); If (pdhstatus = error_success) {// close successfully} else {// close Failed}

Is it easy! In the above example, the pdhaddcounter function is used to add a counter. Its second parameter is the counter address. We can replace other parameters to obtain other counting data. (For details, refer to msdn) Windows performance counters can obtain hundreds of System Counting information, almost all counting-related information. A friend must ask: "What other information can I get? What does so many counters mean ?", Let's continue to look down.
As mentioned above, to obtain other technical information, you only need to change the counter address (that is, the second parameter "/process (" QQ ")/% processor time" in the pdhaddcounter function "), each counter address contains three parts (counter object process, counter % processor time, counter instance qq ), we only need to know what counter objects are in your system, what counters each counter object contains, and what counter instances each counter has, according to the preceding call format, you can obtain all the counting information you want.
Microsoft provides us with a convenient way to obtain counter objects, counters, and instance information-enumeration. You need to use the following APIs to pull a counter:

1. Pin counter object

Pdhenumobjects (null, // [in] data source, NT4.0 must be nullszmachinename, // [in] machine name. The local machine is nullszobjectlistbuffer, // [out] The buffer for receiving the counter list. If the counter list length is 0, this item is blank & dwobjectlistsize, // [in/out] sets or receives the length of the counter list to dwdetaillevel, // gets the information level // perf_detail_novice preliminary level // perf_detail_advance advanced level (including elementary level) // perf_detail_expert level (including beginner and advanced) // perf_detail_wizard system level (including all levels) True );

2. Stick counter and counter instance

Pdhenumobjectitems (null, // [in] data source, NT4.0 must be nullszmachinename, // [in] machine name. The local machine is nullpctcounter, // [in] counter name szcounterlistbuffer, // [out] receives the buffer of the counter list. If the counter list length is 0, this item is blank & dwcounterlistsize, // [in/out] sets or receives the length of the counter list szinstancelistbuffer, // [out] receives the buffer of the Instance list. If the counter list length is 0, this item is blank & dwinstancelistsize, // [in/out] sets or receives the length of the Instance list dwdetaillevel, // gets the information level // perf_detail_novice preliminary level // perf_detail_advance advanced level (including elementary level) // perf_detail_expert level (including elementary and advanced) // perf_detail_wizard system level (including all levels) 0); // The last parameter system is reserved as 0

For more information, see msdn

The basic steps for enumerating counter objects are:

  1. Obtains the size of the counter Object List;
  2. Allocate a buffer for the counter list;
  3. Start to stick;

The following is a programming implementation:
Step 1: Get the counter Object List size

Lptstrszobjectlistbuffer = NULL; dworddwobjectlistsize = 0; lptstrszthisobject = NULL ;__ try {// obtain the buffer size pdhstatus = pdhenumobjects (null, // [in] data source, NT4.0 must be nullnull, // [in] machine name. The local machine is nullszobjectlistbuffer, // [out] The buffer for receiving the counter list. If the counter list length is 0, this item is blank & dwobjectlistsize, // [in/out] sets or receives the length of the counter list perf_detail_wizard, // gets the information level // perf_detail_novice preliminary level // perf_detail_advance advanced level (including elementary level) // perf_detail_expert level (including beginner and advanced) // perf_detail_wizard system level (including all levels) True); If (pdhstatus! = Error_success) {__ leave;} // counter Object List Buffer Memory szobjectlistbuffer = (lptstr) malloc (dwobjectlistsize * sizeof (tchar) based on the obtained buffer size ))); if (szobjectlistbuffer = NULL) {__ leave;} // call this function for the second time to obtain the counter object pdhstatus = pdhenumobjects (null, // [in] data source, NT4.0 must be nullnull, // [in] machine name. The local machine is nullszobjectlistbuffer, // [out] The buffer for receiving the counter list. If the counter list length is 0, this item is blank & dwobjectlistsize, // [in/out] sets or receives the length of the counter list perf_detail_wizard, // gets the information level // perf_detail_novice preliminary level // perf_detail_advance advanced level (including elementary level) // perf_detail_expert level (including beginner and advanced) // perf_detail_wizard system level (including all levels) True); If (pdhstatus! = Error_success) {__ leave;} szthisobject = szobjectlistbuffer; // start the rod for (; * szthisobject! = 0; szthisobject + = (lstrlen (szthisobject) + 1) {// each cycle, szthisobject is the counter object raised by the rod }__ finally {If (abnormaltermination ()) {// if the request fails, if (szobjectlistbuffer! = NULL) {free (szobjectlistbuffer); szobjectlistbuffer = NULL ;}} else {// If successful }}

Don't forget free.

After obtaining the counter object, you can continue the counter and counter instance under this object. The method is basically the same as above. Interested friends can do it by themselves, I will not repeat the space limit.
I am talking about how to know the counter description (Chinese !), That is, What does each counter mean? What is it? You need to use the pdhgetcounterinfo function to know the description of each counter (all operations starting with PDH are called ).

The basic steps are as follows:

1,To Format a counter address (string), you must note that many counters do not have instances. The format of an instance is slightly different from that of an instance. For example:
(With instances) Get the byte speed transmitted to the disk during the current write operation: you need to use the "physicaldisk" counter object, the "disk write Bytes/sec" counter under the counter object, and the counter instance (the instance of the master hard disk on my host is "0 C: d: e: F: "), then the counter address for getting the byte speed I sent to the master hard disk is:"/physicaldisk ("0 C: D: e: F: ")/disk write Bytes/sec ".
(Without instance) obtain the time (in seconds) that the computer has run since its last startup ): if you need to use the "System" counter object, the "system up time" counter under the counter object, and no instance, the address is: "/system up time ".
2,Create a counter pdhaddcounter
3,Allocate a buffer for receiving description information
4,Get description information

The program implementation is as follows:

_ Try {// create counter pdhstatus = pdhaddcounter (hquery, _ text ("// system up time"), 0, pcounterhandle); If (pdhstatus! = Error_success) {__ leave;} // allocate the buffer zone DWORD dwcounterbuff that receives the description; byte bycounterbuff [sizeof (pdh_counter_info) + sizeof (tchar) * 2048]; dwcounterbuff = sizeof (bycounterbuff); // obtain the description pdhstatus = pdhgetcounterinfo (* pcounterhandle, true, & dwcounterbuff, (distinct) bycounterbuff); If (pdhstatus! = Error_success) {__ leave;} pdh_counter_info pdhcounterinfo = * (Counter) bycounterbuff; // For details about the structure of pdh_counter_info, see the msdn // pdh_counter_info structure, szexplaintext indicates the counter description // pdhcounterinfo. szexplaintext }__ finally {If (abnormaltermination () {// If Failed} else {// If successful }}

So far, a brief introduction to performance counters has been completed. I have mentioned a series of topics in the previous article, mainly considering the friends who have just been in touch with VC. It would be a great honor if I could help them in this article. Those with a little VC programming experience will surely sneer at this article. I hope you will not attack me in words for the majority of beginners (including me. I hope that experienced friends can give more valuable comments and make more corrections.

Note:

  1. This article uses unicode encoding, where some macros are used. If you want to compile the code without modification, select unicode encoding in the compiler, add # include to the header file (the file can be run under ANSI encoding with slight modifications );
  2. The _ Try {}__ finally {} used in this article only processes seh for structural exceptions;
  3. If you need the example project and source code of this article, please download www.clock.5888.com on my homepage;
  4. Performance counters can only be used in the 2000/XP system (2003 never tried );
  5. The code compilation environment in this article is Windows 2000 + vc.net;
  6. You are welcome to repost the article. Please indicate the author and source of the article;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.