为什么铬实现Time :: Now?有什么好处?

时间:2016-04-08 06:56:21

标签: c++ chromium

代码段如下,代码来自铬,为什么?

// Initilalize initial_ticks and initial_time
void InitializeClock() {
  initial_ticks = TimeTicks::Now();
  // Initilalize initial_time 
  initial_time = CurrentWallclockMicroseconds();
}// static
Time Time::Now() {
  if (initial_time == 0)
    InitializeClock();

  // We implement time using the high-resolution timers so that we can get
  // timeouts which are smaller than 10-15ms.  If we just used
  // CurrentWallclockMicroseconds(), we'd have the less-granular timer.
  //
  // To make this work, we initialize the clock (initial_time) and the
  // counter (initial_ctr).  To compute the initial time, we can check
  // the number of ticks that have elapsed, and compute the delta.
  //
  // To avoid any drift, we periodically resync the counters to the system
  // clock.
  while (true) {
    TimeTicks ticks = TimeTicks::Now();

    // Calculate the time elapsed since we started our timer
    TimeDelta elapsed = ticks - initial_ticks;

    // Check if enough time has elapsed that we need to resync the clock.
    if (elapsed.InMilliseconds() > kMaxMillisecondsToAvoidDrift) {
      InitializeClock();
      continue;
    }

    return Time(elapsed + Time(initial_time));
  }
}

1 个答案:

答案 0 :(得分:2)

我认为你的答案在于你粘贴的代码的评论:

// We implement time using the high-resolution timers so that we can get
// timeouts which are smaller than 10-15ms.  If we just used
// CurrentWallclockMicroseconds(), we'd have the less-granular timer.

所以Now给出了高分辨率的时间值,当你需要比10-15ms更高的分辨率时这是有益的,因为它们在评论中说明。例如,如果你想每100秒重新安排一个任务,你需要更高的分辨率,或者如果你想测量一些东西的执行时间 - 10-15毫秒是永恒的。