在要求误差不大于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);
}