Search code examples
c++windowsperformancecounterperfmon

how to read windows perfmon counter?


can I get a C++ code to read windows perfmon counter (category, counter name and instance name)?

It's very easy in c# but I needed c++ code.

Thanks


Solution

  • As Doug T. pointed out earlier, I posted a helper class awhile ago to query the performance counter value. The usage of the class is pretty simple, all you have to do is to provide the string for the performance counter. http://askldjd.wordpress.com/2011/01/05/a-pdh-helper-class-cpdhquery/

    However, the code I posted on my blog has been modified in practice. From your comment, it seems like you are interested in querying just a single field.

    In this case, try adding the following function to my CPdhQuery class.

    double CPdhQuery::CollectSingleData()
    {
        double data = 0;
        while(true)
        {
            status = PdhCollectQueryData(hQuery);
    
            if (ERROR_SUCCESS != status)
            {
                throw CException(GetErrorString(status));
            }
    
            PDH_FMT_COUNTERVALUE cv;
            // Format the performance data record.
            status = PdhGetFormattedCounterValue(hCounter,
                PDH_FMT_DOUBLE,
                (LPDWORD)NULL,
                &cv);
    
            if (ERROR_SUCCESS != status)
            {
                continue;
            }
    
            data = cv.doubleValue;
    
            break;
    
        }
    
        return data;
    }
    

    For e.g. To get processor time

    counter = boost::make_shared<CPdhQuery>(std::tstring(_T("\\Processor Information(_Total)\% Processor Time")));
    

    To get file read bytes / sec:

    counter = boost::make_shared<CPdhQuery>(std::tstring(_T("\\System\\File Read Bytes/sec")));
    

    To get % Committed Bytes:

    counter = boost::make_shared<CPdhQuery>(std::tstring(_T("\\Memory\\% Committed Bytes In Use")));
    

    To get the data, do this.

    double data = counter->CollectSingleData();
    

    I hope this helps.

    ... Alan