When QueryPerformanceCounter Fails

Here’s a bug I’d never heard about before: On certain hardware / OS combinations, QueryPerformanceCounter can return incorrect results if it isn’t called frequently enough.

IB PLANalyzer uses this function to profile query execution, so if you find unrealisticly low times for query execution you may be seeing this problem.

Brian Cook posted the following Delphi code which will test to see if you have this problem on your system:


program Project2;

{$APPTYPE CONSOLE}

uses
  Windows;

var
  Frequency: Int64;
  Start: Int64;
  Stop: Int64;
  Delta: Int64;
  Elapsed: Extended;
  I: Integer;

begin
  QueryPerformanceFrequency( Frequency );
  Writeln( 'Frequency: ', Frequency );

  for I := 1 to 10 do
  begin
    QueryPerformanceCounter( Start );
    Sleep( I * 1000 );
    QueryPerformanceCounter( Stop );
    Delta := (Stop - Start);
    Elapsed := Delta / Frequency;
    Writeln( I:2, ' seconds:', Elapsed:6:3 );
  end;

  if DebugHook <> 0 then
    Readln;
end.

When you run this app you should get numbers which are very close to 1-10. If a couple of the lines have times much lower than they should be then your OS/hardware are affected by the bug.