title: Why doesn't my performance counter code work?
body: <p>I am trying to use the Windows performance counters to get the virtual bytes usage of a specific process.  It seemed simpler to read the % CPU usage, so I thought I would try to get that to work first.</p>
  
  <p>At the top of the file, I have this:</p>
  
  <pre><code>#include &lt;pdh.h&gt;
  #include &lt;pdhmsg.h&gt;
  </code></pre>
  
  <p>Then in a function, I have this:</p>
  
  <pre><code>PDH_STATUS status = ERROR_SUCCESS;
  
  PDH_HQUERY query = NULL;
  status = PdhOpenQuery(
      NULL,
      0,
      &amp;query);
  CHECK(status == ERROR_SUCCESS, L"Couldn't create query.");
  
  PDH_HCOUNTER counter = NULL;
  status = PdhAddCounter(query, L"\\Processor(_Total)\\% Processor Time", 0, &amp;counter);
  CHECK(status == ERROR_SUCCESS, L"Couldn't add counter.");
  
  status = PdhCollectQueryData(query);
  CHECK(status == ERROR_SUCCESS, L"Couldn't collect query data.");
  Sleep(2000);
  
  status = PdhCollectQueryData(query);
  CHECK(status == ERROR_SUCCESS, L"Couldn't collect query data.");
  Sleep(2000);
  
  PDH_RAW_COUNTER rawValue;
  status = PdhGetRawCounterValue(&amp;counter, NULL, &amp;rawValue);
  CHECK(status == ERROR_SUCCESS, L"Couldn't get the raw counter value.");
  
  status = PdhCloseQuery(&amp;query);
  CHECK(status == ERROR_SUCCESS, L"Couldn't close the query handle.");
  </code></pre>
  
  <p>CHECK is macro that is used on the project to assert.  The status is ERROR_SUCCESS at every call until the call to PdhGetRawCounterValue().  When I call that function, the result is 0xC0000BBC which is defined in pdhmsg.h as PDH_INVALID_HANDLE.  The reason for the call to Sleep() is that <a href="http://msdn.microsoft.com/en-us/library/aa371897%28v=VS.85%29.aspx" rel="nofollow">this page</a> says you need to read two samples for some counters and wait at least one second in between.</p>
  
  <p>Am I doing something wrong?</p>