C++Builder logo
Need a High resolution counter? Besoin d'un compteur à haute résolution

With the TTimer and multimedia timer, you can't define an interval less than about 1 ms. On the other hand, Windows provides two API functions to access a high resolution counter : QueryPerformanceFrequency() and QueryPerformanceCounter(). The first function retrieves the frequency at which the counter is updated and the second function retrieves the value of the counter. Be aware that the resolution is hardware dependent. The counter is reseted each time you re-boot your computer.

The example below gets the value of the counter and calculates the time since the last boot.

Le composant TTimer et le timer multimédia ne permettent pas d'obtenir une résolution meilleure que 1 ms. Deux fonctions de l'API permettent, par contre, d'accéder à la valeur d'un compteur hardware : QueryPerformanceFrequency() et QueryPerformanceCounter(). La première fonction retourne la fréquence à laquelle le compteur est mis à jour, la seconde retourne la valeur du compteur. Gardez à l'esprit que ce compteur est dépendant du hardware. Ce compteur est remis à zéro à chaque boot du PC.

L'exemple, ci-dessous, calcule le temps écoulé depuis le dernier boot.


LARGE_INTEGER freq,counter,sec,time;
//retrieve the frequency of the high resolution counter
QueryPerformanceFrequency(&freq);
//retrieve the value of the counter
//the counter is incremented every freq-th of a second
QueryPerformanceCounter(&counter);
//divide the counter value by the frequency
sec.QuadPart=counter.QuadPart/freq.QuadPart;    
//get the number of hours
int h=sec.QuadPart/3600;
//get the number of minutes
time.QuadPart=sec.QuadPart-(h*3600);
int m=time.QuadPart/60;
//get the number of seconds
time.QuadPart=time.QuadPart-(m*60);
//build an AnsiString containing the h:m:s
AnsiString hour=IntToStr(h);
hour+=" h ";
hour+=IntToStr(m);
hour+=" m ";
hour+=IntToStr(time.QuadPart);
hour+=" s";
Label1->Caption=hour;