Access Raw Data with Performance Counters in Visual C++

Access Raw Data with Performance Counters in Visual C++

indows lets you monitor a large number of internal statistics. Most people only see them in the Performance Monitor utility. This is fine if all you need is to look at graphs, but to fully study and analyze the information, you’ll need to get at the raw data. Windows gives you access to the raw data, but only through a cumbersome C API. However, with the proper application of a few C++ techniques, you can make the whole process much simpler.

Working with (and Wrapping) Queries
At the lowest level, the structures used are defined in the Platform SDK header . Microsoft apparently realized that those were too tedious for most people to use, so they built a new interface on top of that, known as the Performance Data Helper (PDH) interface. Though the PDH was only a slight improvement, you can still build a useable interface with it.

The structure at the heart of performance monitoring is the HQUERY. It is initialized with the API function PdhOpenQuery(), and closed out with PdhCloseQuery(). Clearly this calls for a wrapper class, which I’ll call Query, with a constructor and destructor handling these tasks. The main purpose for a HQUERY is to manage a number of HCOUNTER structures. They are attached to a HQUERY by calling PdhAddCounter(). Add a member function to Query to attach them. Also add a cast to access the underlying HQUERY, and you have a functioning minimal interface for Query (see Listing 1). It’s fairly simple, and if that were all, I might not have even bothered with the C++ wrapper. But there is more. The next piece is the HCOUNTER structure. Every value you wish to monitor gets one HCOUNTER, and all of them are managed by the HQUERY (or, by the Query class). However, wrapping the HCOUNTER poses a special challenge. You create it, but it must be filled by another process–the one that’s being monitored. This means it needs to exist in Shared Global Memory. You never have a HCOUNTER; you have to use a pointer to an HCOUNTER, and allocate the HCOUNTER with GlobalAlloc(). This greatly complicates making a wrapper class.

At first, you might decide to store a HCOUNTER* as the class’s sole data member, calling GlobalAlloc in the constructor and GlobalFree in the destructor. This method is problematic. You’ll need to write a copy constructor as well, but how should that work? Normally, the copy constructor would allocate a new block of memory and copy the data from one to the other. The problem is that this block, by its very nature, is shared. Some other program is both looking at and writing to it. If you allocate a new block, they may be identical for a moment, but the other process will still be writing to the first one.

Another solution is to have just one memory block, and simply pass a pointer around to it. In this case, you can’t have the destructor free the block. For example, if you were to return such an object from a function (which is something you will want to do), you create a new object by calling the copy constructor (copying just the pointer), and then the original object goes out of scope as the function ends (and its destructor is called, freeing the block). But removing the allocation/deallocation from the constructor/destructor leaves you with the wrapper class doing nothing at all. It was supposed to make working with a HCOUNTER simpler! You need a reference counted pointer to keep track of how many pointers to the block are being used, and to automatically delete the block only after all references to it are destroyed.

Smart Pointers
Pointer classes like this are commonly referred to as “smart pointers”. The best known is auto_ptr, which is now part of the Standard C++ Library. Unfortunately, this leads some to believe that auto_ptr is right for every situation that calls for a smart pointer, but this isn’t so. Auto_ptr has a very specific use, but this is not it.

Writing a reference counted pointer class is not particularly difficult, and is described in a number of reference books. You don’t have to worry about this, however, as the work is already done for you by the good folks at Boost.org. Boost is a public organization developing an open source C++ library of commonly used tools.

One of the very first things added to Boost was the Smart Pointer library, which includes shared_ptr<>. Considering it’s general utility, and growing use, it has a very good chance of being added to the Standard Library when the next C++ Standard is complete (circa 2005 or so). The more it’s used now, the better the chances it has of becoming part of the Standard.Shared_ptr is a simple “drop-in” class to handle reference counting. Just say “boost::shared_ptr” and that’s it. Well, that’s almost it. Shared_ptr will destroy the object it’s holding using delete, so you create it using new. But the standard new allocates memory in your local memory space, and you need it in shared global memory. Fortunately, C++ provides the tools for that as well, and you don’t even have to leave the current Standard. Simply define class-specific new and delete functions.

struct GlobalCounter{   void * operator new(size_t )   {  return GlobalAlloc(GPTR,sizeof(HCOUNTER)); }   void operator delete(void * ptr)   {  GlobalFree(ptr); }   HCOUNTER* handle()     { return (HCOUNTER*) this; }};

When new is called, it allocates enough space from global memory, and frees it on delete. I also added a member function called handle() to get a pointer to the raw memory itself. The version shown here is just for presentation; the version given in the complete source listing is templatized to allow reuse (see Listing 2).

Now that all the pieces are in place, you can finally create a wrapper for a HCOUNTER struct which will allow you to treat it just like any other object.

#include "boost/smart_ptr.hpp"struct  Counter  : public boost::shared_ptr< GlobalCounter > {   Counter () :       boost::shared_ptr< GlobalCounter > (new GlobalCounter )       {}   operator HCOUNTER *() { return get()->handle(); }};

As with GlobalCounter, the full version of the inline code is in the complete source (see Listing 3).

Finally, you have to deal with the essence of performance counters. You have one or more Counter objects, which are created and managed by a Query object. So, request a new counter by adding it to the Query object, which provides it with a Counter object. To determine what values the counter totals, ask the Query object to Collect the data. The values will appear in the Counter objects.

Query	hQuery;Counter counter =     hQuery.AddCounter(_T("\TCP\Connections Established"));hQuery.Collect();

The string passed to AddCounter describes the value you want to monitor. They follow the basic format “\MachinePerfObject(ParentInstance/ObjectInstance#InstanceIndex)Counter.” Some of those pieces are optional. For example, in the above code, you have TCPConnections Established”, which has just the PerfObject and Counter parts. Similarly, you could have \Mach02Process(Explorer)\% Processor Time to find the processor time used by Explorer.exe on a remote PC called “Mach02.”

A full list of the monitored values isn’t possible since the system is extensible to user-defined counters. However, you can use other functions in the PDH to get a partial list. These functions can be found by looking at the options in PerfMon.

Now that you have the value you want in the Counter, you need to get it out. This poses a new problem, as the format of the count varies depending on what’s being counted. Sometimes it’s a long and sometimes it a double, or LONGLONG, or a string. And to make things even more complicated, you have to ask the OS to convert the counter into any of those forms. I’ve added a few more member functions to Counter, to simplify this. Each comes in two variations: One to return the value as the native type (Counter::asDouble for example), and another to return the value converted to a std::string (Counter:: asLongString). If an error occurs, say, when you ask for the value in an incompatible type, the string functions return “(error)” while the native type functions throw an exception.

devx-admin

devx-admin

Share the Post:
Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years,

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW)

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the