在要求誤差不大于1毫秒的情況下,可以采用GetTickCount()函數(shù),該函數(shù)的返回值是DWORD型,表示以毫秒為單位的計(jì)算機(jī)啟動(dòng)后經(jīng)歷的時(shí)間間隔。使用下面的編程語(yǔ)句,可以實(shí)現(xiàn)50毫秒的精確定時(shí),其誤差小于1毫秒。
對(duì)于一般的實(shí)時(shí)控制,使用GetTickCount()函數(shù)就可以滿足精度要求,但要進(jìn)一步提高計(jì)時(shí)精度,就要采用QueryPerformanceFrequency()函數(shù)和QueryPerformanceCounter()函數(shù)。
這兩個(gè)函數(shù)是VC提供的僅供Windows使用的高精度時(shí)間函數(shù),并要求計(jì)算機(jī)從硬件上支持高精度計(jì)時(shí)器。QueryPerformanceFrequency()函數(shù)和QueryPerformanceCounter()函數(shù)的原型為:
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);
}