time_mac.cc 8.41 KB
Newer Older
gejun's avatar
gejun committed
1 2 3 4
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "butil/time/time.h"
gejun's avatar
gejun committed
6 7 8 9 10 11 12 13 14 15

#include <CoreFoundation/CFDate.h>
#include <CoreFoundation/CFTimeZone.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>

16 17 18 19
#include "butil/basictypes.h"
#include "butil/logging.h"
#include "butil/mac/scoped_cftyperef.h"
#include "butil/mac/scoped_mach_port.h"
gejun's avatar
gejun committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33

namespace {

uint64_t ComputeCurrentTicks() {
#if defined(OS_IOS)
  // On iOS mach_absolute_time stops while the device is sleeping. Instead use
  // now - KERN_BOOTTIME to get a time difference that is not impacted by clock
  // changes. KERN_BOOTTIME will be updated by the system whenever the system
  // clock change.
  struct timeval boottime;
  int mib[2] = {CTL_KERN, KERN_BOOTTIME};
  size_t size = sizeof(boottime);
  int kr = sysctl(mib, arraysize(mib), &boottime, &size, NULL, 0);
  DCHECK_EQ(KERN_SUCCESS, kr);
34 35 36
  butil::TimeDelta time_difference = butil::Time::Now() -
      (butil::Time::FromTimeT(boottime.tv_sec) +
       butil::TimeDelta::FromMicroseconds(boottime.tv_usec));
gejun's avatar
gejun committed
37 38 39 40 41 42 43 44 45 46 47 48
  return time_difference.InMicroseconds();
#else
  uint64_t absolute_micro;

  static mach_timebase_info_data_t timebase_info;
  if (timebase_info.denom == 0) {
    // Zero-initialization of statics guarantees that denom will be 0 before
    // calling mach_timebase_info.  mach_timebase_info will never set denom to
    // 0 as that would be invalid, so the zero-check can be used to determine
    // whether mach_timebase_info has already been called.  This is
    // recommended by Apple's QA1398.
    kern_return_t kr = mach_timebase_info(&timebase_info);
49
    DCHECK(kr == KERN_SUCCESS) << "Fail to call mach_timebase_info";
gejun's avatar
gejun committed
50 51 52 53 54 55 56 57 58
  }

  // mach_absolute_time is it when it comes to ticks on the Mac.  Other calls
  // with less precision (such as TickCount) just call through to
  // mach_absolute_time.

  // timebase_info converts absolute time tick units into nanoseconds.  Convert
  // to microseconds up front to stave off overflows.
  absolute_micro =
59
      mach_absolute_time() / butil::Time::kNanosecondsPerMicrosecond *
gejun's avatar
gejun committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73
      timebase_info.numer / timebase_info.denom;

  // Don't bother with the rollover handling that the Windows version does.
  // With numer and denom = 1 (the expected case), the 64-bit absolute time
  // reported in nanoseconds is enough to last nearly 585 years.
  return absolute_micro;
#endif  // defined(OS_IOS)
}

uint64_t ComputeThreadTicks() {
#if defined(OS_IOS)
  NOTREACHED();
  return 0;
#else
74
  butil::mac::ScopedMachSendRight thread(mach_thread_self());
gejun's avatar
gejun committed
75 76 77 78 79 80 81 82 83
  mach_msg_type_number_t thread_info_count = THREAD_BASIC_INFO_COUNT;
  thread_basic_info_data_t thread_info_data;

  if (thread.get() == MACH_PORT_NULL) {
    DLOG(ERROR) << "Failed to get mach_thread_self()";
    return 0;
  }

  kern_return_t kr = thread_info(
84
      thread.get(),
gejun's avatar
gejun committed
85 86 87
      THREAD_BASIC_INFO,
      reinterpret_cast<thread_info_t>(&thread_info_data),
      &thread_info_count);
88
  DCHECK(kr == KERN_SUCCESS) << "Fail to call thread_info";
gejun's avatar
gejun committed
89 90

  return (thread_info_data.user_time.seconds *
91
              butil::Time::kMicrosecondsPerSecond) +
gejun's avatar
gejun committed
92 93 94 95 96 97
         thread_info_data.user_time.microseconds;
#endif  // defined(OS_IOS)
}

}  // namespace

98
namespace butil {
gejun's avatar
gejun committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

// The Time routines in this file use Mach and CoreFoundation APIs, since the
// POSIX definition of time_t in Mac OS X wraps around after 2038--and
// there are already cookie expiration dates, etc., past that time out in
// the field.  Using CFDate prevents that problem, and using mach_absolute_time
// for TimeTicks gives us nice high-resolution interval timing.

// Time -----------------------------------------------------------------------

// Core Foundation uses a double second count since 2001-01-01 00:00:00 UTC.
// The UNIX epoch is 1970-01-01 00:00:00 UTC.
// Windows uses a Gregorian epoch of 1601.  We need to match this internally
// so that our time representations match across all platforms.  See bug 14734.
//   irb(main):010:0> Time.at(0).getutc()
//   => Thu Jan 01 00:00:00 UTC 1970
//   irb(main):011:0> Time.at(-11644473600).getutc()
//   => Mon Jan 01 00:00:00 UTC 1601
static const int64_t kWindowsEpochDeltaSeconds = GG_INT64_C(11644473600);

// static
const int64_t Time::kWindowsEpochDeltaMicroseconds =
    kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;

// Some functions in time.cc use time_t directly, so we provide an offset
// to convert from time_t (Unix epoch) and internal (Windows epoch).
// static
const int64_t Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;

// static
Time Time::Now() {
  return FromCFAbsoluteTime(CFAbsoluteTimeGetCurrent());
}

// static
Time Time::FromCFAbsoluteTime(CFAbsoluteTime t) {
  COMPILE_ASSERT(std::numeric_limits<CFAbsoluteTime>::has_infinity,
                 numeric_limits_infinity_is_undefined_when_not_has_infinity);
  if (t == 0)
    return Time();  // Consider 0 as a null Time.
  if (t == std::numeric_limits<CFAbsoluteTime>::infinity())
    return Max();
  return Time(static_cast<int64_t>(
      (t + kCFAbsoluteTimeIntervalSince1970) * kMicrosecondsPerSecond) +
      kWindowsEpochDeltaMicroseconds);
}

CFAbsoluteTime Time::ToCFAbsoluteTime() const {
  COMPILE_ASSERT(std::numeric_limits<CFAbsoluteTime>::has_infinity,
                 numeric_limits_infinity_is_undefined_when_not_has_infinity);
  if (is_null())
    return 0;  // Consider 0 as a null Time.
  if (is_max())
    return std::numeric_limits<CFAbsoluteTime>::infinity();
  return (static_cast<CFAbsoluteTime>(us_ - kWindowsEpochDeltaMicroseconds) /
      kMicrosecondsPerSecond) - kCFAbsoluteTimeIntervalSince1970;
}

// static
Time Time::NowFromSystemTime() {
  // Just use Now() because Now() returns the system time.
  return Now();
}

// static
Time Time::FromExploded(bool is_local, const Exploded& exploded) {
  CFGregorianDate date;
  date.second = exploded.second +
      exploded.millisecond / static_cast<double>(kMillisecondsPerSecond);
  date.minute = exploded.minute;
  date.hour = exploded.hour;
  date.day = exploded.day_of_month;
  date.month = exploded.month;
  date.year = exploded.year;

173
  butil::ScopedCFTypeRef<CFTimeZoneRef> time_zone(
gejun's avatar
gejun committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
      is_local ? CFTimeZoneCopySystem() : NULL);
  CFAbsoluteTime seconds = CFGregorianDateGetAbsoluteTime(date, time_zone) +
      kCFAbsoluteTimeIntervalSince1970;
  return Time(static_cast<int64_t>(seconds * kMicrosecondsPerSecond) +
      kWindowsEpochDeltaMicroseconds);
}

void Time::Explode(bool is_local, Exploded* exploded) const {
  // Avoid rounding issues, by only putting the integral number of seconds
  // (rounded towards -infinity) into a |CFAbsoluteTime| (which is a |double|).
  int64_t microsecond = us_ % kMicrosecondsPerSecond;
  if (microsecond < 0)
    microsecond += kMicrosecondsPerSecond;
  CFAbsoluteTime seconds = ((us_ - microsecond) / kMicrosecondsPerSecond) -
                           kWindowsEpochDeltaSeconds -
                           kCFAbsoluteTimeIntervalSince1970;

191
  butil::ScopedCFTypeRef<CFTimeZoneRef> time_zone(
gejun's avatar
gejun committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
      is_local ? CFTimeZoneCopySystem() : NULL);
  CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(seconds, time_zone);
  // 1 = Monday, ..., 7 = Sunday.
  int cf_day_of_week = CFAbsoluteTimeGetDayOfWeek(seconds, time_zone);

  exploded->year = date.year;
  exploded->month = date.month;
  exploded->day_of_week = cf_day_of_week % 7;
  exploded->day_of_month = date.day;
  exploded->hour = date.hour;
  exploded->minute = date.minute;
  // Make sure seconds are rounded down towards -infinity.
  exploded->second = floor(date.second);
  // Calculate milliseconds ourselves, since we rounded the |seconds|, making
  // sure to round towards -infinity.
  exploded->millisecond =
      (microsecond >= 0) ? microsecond / kMicrosecondsPerMillisecond :
                           (microsecond - kMicrosecondsPerMillisecond + 1) /
                               kMicrosecondsPerMillisecond;
}

// TimeTicks ------------------------------------------------------------------

// static
TimeTicks TimeTicks::Now() {
  return TimeTicks(ComputeCurrentTicks());
}

// static
TimeTicks TimeTicks::HighResNow() {
  return Now();
}

// static
bool TimeTicks::IsHighResNowFastAndReliable() {
  return true;
}

// static
TimeTicks TimeTicks::ThreadNow() {
  return TimeTicks(ComputeThreadTicks());
}

// static
TimeTicks TimeTicks::NowFromSystemTraceTime() {
  return HighResNow();
}

240
}  // namespace butil