在要求誤差不大于1毫秒的情況下,可以采用GetTickCount()函數,該函數的返回值是DWORD型,表示以毫秒為單位的計算機啟動后經歷的時間間隔。使用下面的編程語句,可以實現50毫秒的精確定時,其誤差小于1毫秒。
對于一般的實時控制,使用GetTickCount()函數就可以滿足精度要求,但要進一步提高計時精度,就要采用QueryPerformanceFrequency()函數和QueryPerformanceCounter()函數。
這兩個函數是VC提供的僅供Windows使用的高精度時間函數,并要求計算機從硬件上支持高精度計時器。QueryPerformanceFrequency()函數和QueryPerformanceCounter()函數的原型為:
The QueryPerformanceFrequency function retrieves the frequency of the high-resolution performance counter, if one exists. The frequency cannot change while the system is running.
BOOL QueryPerformanceFrequency(
LARGE_INTEGER *lpFrequency
);
Parameters
lpFrequency
[out] Pointer to a variable that receives the current performance-counter frequency, in counts per second. If the installed hardware does not support a high-resolution performance counter, this parameter can be zero.
Return Value
If the installed hardware supports a high-resolution performance counter, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError. For example, if the installed hardware does not support a high-resolution performance counter, the function fails.
The QueryPerformanceCounter function retrieves the current value of the high-resolution performance counter.
BOOL QueryPerformanceCounter(
LARGE_INTEGER *lpPerformanceCount
);
Parameters
lpPerformanceCount
[out] Pointer to a variable that receives the current performance-counter value, in counts.
Return Value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Linux下的:
#include <sys/time.h>
unsigned long GetTickCount()
{
struct timeval tv;
if (gettimeofday(&tv,NULL) !=0) {
return 0;
}
return (tv.tv_sec*1000)+(tv.tv_usec/1000);
}