高解析度計時器
之從寫出55ms解析度的計數器之後

就不斷去嘗試如何寫出以m sec或μsec

有一位來自《Experts-Exchange.com:zebada》提供一份資料

註釋的部份是我附加上去的,詳細的部份可參考MSDN


For an x86 platform I presume?

This code will get down to 1/3 of a microsecond if your motherboard has a 

high frequency timer circuit on it. Most modern motherboards do.

Here's the code followed by the output:


#include <stdio.h>

#include <windows.h>



int main(int argc, char *argv[])

{

 //The LARGE_INTEGER structure is used to represent

 //a 64-bit signed integer value.

 LARGE_INTEGER f,t1,t2,e;

 double uf;

  /* 

    Size Prefixes for printf and wprintf Format-Type Specifiers

        To specify     Use prefix  With type specifier

        __int64        I64          d, i, o, u, x, or X 

  */

  /* 

        The LARGE_INTEGER structure is actually a union. If your compiler

         has built-in support for 64-bit integers, use the QuadPart member

         to store the 64-bit integer. Otherwise, use the LowPart and HighPart

         members to store the 64-bit integer.

         

         BOOL QueryPerformanceFrequency( LARGE_INTEGER* lpFrequency );

         Parameters:lpFrequency 

         [out] Pointer to a variable that receives the current 

         performance-counter frequency, in counts per second. 

  */

 QueryPerformanceFrequency(&f);

 printf("Frequency (counts per second) %I64d\n",f.QuadPart);

 uf = f.QuadPart/1000000.0;

 printf("Frequency (counts per microsecond) %lf\n",uf);

 QueryPerformanceCounter(&t1);

 Sleep(1000);  

 QueryPerformanceCounter(&t2);

 e.QuadPart = (t2.QuadPart-t1.QuadPart);

 printf("Elapsed counts %I64d\n",e.QuadPart);

 printf("Elapsed microseconds %lf\n",e.QuadPart/uf);



 return 0;

}



Frequency (counts per second) 3579545

Frequency (counts per microsecond) 3.579545

Elapsed counts 3580714

Elapsed microseconds 1000326.577819



If you want to get finer than this you may need to investigate the pentium

specific timestamp opcode - can't remember what it is - but it will measure

times in CPU clock cycles.



Regards

Paul 



經過修改之後就可以得到大約0.28mSec解析度的計數器(測試環境VC6.0)

#include <stdio.h>

#include <conio.h>  //for kbhit()

#include 




int main(int argc, char *argv[])

{

         LARGE_INTEGER    f,start_count,end_count,elapse;

         long int count_per_sec;



         QueryPerformanceFrequency(&f);

         count_per_sec = f.QuadPart;



         QueryPerformanceCounter(&start_count);

         for(  ;!kbhit(); )        

         {                

                 QueryPerformanceCounter(&end_count);

                 elapse.QuadPart = (end_count.QuadPart-start_count.QuadPart);

                 printf("Elapsed microseconds:%.6lf\r",elapse.QuadPart/(double)count_per_sec);

         }        

         printf("\n");

         return 0;

}

Elapsed microseconds:2.630882


回目錄
Written By James On 2004/02/08 

 

Hosted by www.Geocities.ws

1