1

我需要使用 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);
}
4

2 回答 2

1

此处无需使用uint64_t-unsigned long long保证至少为 64 位宽。

您也不需要往返于double,因为NTP_SCALE_FRAC * 1000000它很容易适应unsigned long long.

EPOCH应该是unsigned long long,不是unsigned long,这样加法 withtv.tv_sec不会环绕。

全部起来:

const unsigned long long EPOCH = 2208988800ULL;
const unsigned long long NTP_SCALE_FRAC = 4294967296ULL;

unsigned long long tv_to_ntp(struct timeval tv)
{
    unsigned long long tv_ntp, tv_usecs;

    tv_ntp = tv.tv_sec + EPOCH;
    tv_usecs = (NTP_SCALE_FRAC * tv.tv_usec) / 1000000UL;

    return (tv_ntp << 32) | tv_usecs;
}
于 2010-04-15T02:20:46.997 回答
1
extern uint64_t tvtontp64(struct timeval *tv) {
    uint64_t ntpts;

    ntpts = (((uint64_t)tv->tv_sec + 2208988800u) << 32) + ((uint32_t)tv->tv_usec * 4294.967296);

    return (ntpts);
}

我使用的是 4294.967296 而不是 ...5,因为它是与总计数的比率 0 需要计数 4294967296 滴答每秒或 4294.967296 每 usec 它很容易验证这一点,因为 1000000 usec 将是溢出 [to seconds] 范围刻度数应为 0 到 (1000000-1)。

这是一个简化,适合我的目的唯一本地 IPv6 单播地址 [RFC4193]

于 2012-05-20T16:37:09.493 回答