Re: Timing Delphi code for optimization

Posted by John, DelphiLand Team on August 04, 2007

In Reply to Timing code for optimization posted by Willy on August 04, 2007

: There are several functions that I can use for timing the performance of my Delphi code: Now, GetTickCount, QueryPerformanceCounter, etc... I've read somewhere that QueryPerformanceCounter is the most accurate. Is the timing difference really big compared to the other functions? Or is it small enough to ignore?
: How to go about for having a really useful procedure for optimizing code?

Delphi's function Now is limited by the resolution of the Windows system timer. In Windows Me/98/95, the system timer ticks at approximately each 55 msec, in Windows NT/XP at approximately 16 msec. That makes a function like Now not suitable for measuring short time frames. For example, under Windows XP, if you time a process that takes 15 msec, you measure either 0 msec or 16 msec.

The GetTickCount function returns the number of milliseconds elapsed since the system started running. Alas, GetTickCount is no better, it's also limited to the resolution of the system timer.

On the other hand, if a hardware high-resolution performance counter exists on your system (available on most systems nowadays), you can measure time intervals with a resolution of one microsecond. With the function QueryPerformanceFrequency you retrieve the frequency of the counter, and with QueryPerformanceCounter you retrieve the current value of the counter. Here's a Delphi source code example:

  Freq, StartCount, StopCount: Int64;
  TimingSeconds: real;
  // Execute process that you want to time: ...
  TimingSeconds := (StopCount - StartCount) / Freq;
  // Display timing: ...