我需要使用gettimeofday來計算ntp時間戳。以下是我對方法的評論。看起來很好,你們呢? (減去錯誤檢查)。此外,這是一個codepad鏈接。從gettimeofday創建ntp時間戳
#include <unistd.h>
#include <sys/time.h>
const unsigned long EPOCH = 2208988800UL; // delta between epoch time and ntp time
const double NTP_SCALE_FRAC = 4294967295.0; // maximum value of the ntp fractional part
int main()
{
struct timeval tv;
uint64_t ntp_time;
uint64_t tv_ntp;
double tv_usecs;
gettimeofday(&tv, NULL);
tv_ntp = tv.tv_sec + EPOCH;
// convert tv_usec to a fraction of a second
// next, we multiply this fraction times the NTP_SCALE_FRAC, which represents
// the maximum value of the fraction until it rolls over to one. Thus,
// .05 seconds is represented in NTP as (.05 * NTP_SCALE_FRAC)
tv_usecs = (tv.tv_usec * 1e-6) * NTP_SCALE_FRAC;
// next we take the tv_ntp seconds value and shift it 32 bits to the left. This puts the
// seconds in the proper location for NTP time stamps. I recognize this method has an
// overflow hazard if used after around the year 2106
// Next we do a bitwise OR with the tv_usecs cast as a uin32_t, dropping the fractional
// part
ntp_time = ((tv_ntp << 32) | (uint32_t)tv_usecs);
}
我可以問你爲什麼用NTP_SCALE_FRAC乘tv_usec?對我來說,似乎將pico秒(* 10^6)轉換爲usec可能就足夠了,也許我錯過了一些東西? – 2010-05-19 16:34:18
在NTP中,如果我理解正確,分數部分將表示爲總可能值的一小部分。所以這不是1比1。例如,如果我代表1000秒中的一秒鐘,那麼有人給我一個0.5秒的值,基數爲60,我必須將其縮放到我的基數1000. 使用NTP時,基數是它轉換成的32位表示。所以1秒= 2^32 ntp分數秒。 – jkyle 2010-05-19 17:59:11
謝謝,我明白這一點。對我而言不明顯的是爲什麼 tv_usecs =(NTP_SCALE_FRAC * tv.tv_usec)/ 1000000UL 能勝任這項工作嗎? – 2010-05-20 12:20:59