U64 result = 0;
#ifdef _WIN32
U64 tick = GetTickCount64(); // 10-16ms tolerance
U64 time = timeGetTime(); // 1ms tolerance, but 49.5 days limit.
// bias 65536ms [0-65535], this vlaue must be far greater then tick and time's diff.
// if equal, return directly.
result = ( tick & 0xFFFFFFFFFFFF0000 ) | ( time & 0x000000000000FFFF );
// compare result with tick
if( result > tick )
{
// clamp tick to U32_MAX range;
U64 diff = tick & U32_MAX;
// need carry ?
if( tick > U32_MAX ) {
diff |= 0x100000000;
}
// this vlaue usualy less then 16 ms.
diff > time ? diff = diff - time : diff = time - diff;
// if diff out of U32_MAX range, clamp it.
if( diff > U32_MAX ) {
diff &= U32_MAX;
}
// if diff out of U16_MAX range, reverse bits.
if( diff > U16_MAX )
{
if( diff > U32(~diff) ) {
diff = U32(~diff) + U64(1);
}
}
// this value usualy equal to diff.
if( result - tick > diff )
{
result -= 0x10000;
}
}
else
if( result < tick )
{
U64 diff = tick & U32_MAX;
if( tick > U32_MAX ) {
diff |= 0x100000000;
}
// this vlaue usualy less then 16 ms.
diff > time ? diff = diff - time : diff = time - diff;
if( diff > U32_MAX ) {
diff &= U32_MAX;
}
if( diff > U16_MAX )
{
if( diff > U32(~diff) ) {
diff = U32(~diff);
}
}
// this value usualy equal to diff.
if( tick - result > diff )
{
result += 0x10000;
}
}
#endif
return result;
多的不说,直接上代码。。。
Windows下面是没有timeGetTime64这个函数的。因此,timeGetTime返回值(32位)会在49.5天内重置。这样可能会导致一些问题。
想了一个办法,用Windows的另外一个函数GetTickCount64来获取大致时间,这个时间有10-16ms的误差,然后再用timeGetTime获取高精度的授时。然后组合一下。就可以形成U64位的高精度返回值。