1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/time/time.h"
10 #if defined(OS_ANDROID)
18 #include "base/basictypes.h"
19 #include "base/logging.h"
20 #include "base/port.h"
21 #include "build/build_config.h"
23 #if defined(OS_ANDROID)
24 #include "base/os_compat_android.h"
25 #elif defined(OS_NACL)
26 #include "base/os_compat_nacl.h"
31 // Define a system-specific SysTime that wraps either to a time_t or
32 // a time64_t depending on the host system, and associated convertion.
33 // See crbug.com/162007
34 #if defined(OS_ANDROID)
35 typedef time64_t SysTime
;
37 SysTime
SysTimeFromTimeStruct(struct tm
* timestruct
, bool is_local
) {
39 return mktime64(timestruct
);
41 return timegm64(timestruct
);
44 void SysTimeToTimeStruct(SysTime t
, struct tm
* timestruct
, bool is_local
) {
46 localtime64_r(&t
, timestruct
);
48 gmtime64_r(&t
, timestruct
);
52 typedef time_t SysTime
;
54 SysTime
SysTimeFromTimeStruct(struct tm
* timestruct
, bool is_local
) {
56 return mktime(timestruct
);
58 return timegm(timestruct
);
61 void SysTimeToTimeStruct(SysTime t
, struct tm
* timestruct
, bool is_local
) {
63 localtime_r(&t
, timestruct
);
65 gmtime_r(&t
, timestruct
);
69 #if !defined(OS_MACOSX)
70 // Helper function to get results from clock_gettime() as TimeTicks object.
71 // Minimum requirement is MONOTONIC_CLOCK to be supported on the system.
72 // FreeBSD 6 has CLOCK_MONOTONIC but defines _POSIX_MONOTONIC_CLOCK to -1.
73 #if (defined(OS_POSIX) && \
74 defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \
75 defined(OS_BSD) || defined(OS_ANDROID)
76 base::TimeTicks
ClockNow(clockid_t clk_id
) {
77 uint64_t absolute_micro
;
80 if (clock_gettime(clk_id
, &ts
) != 0) {
81 NOTREACHED() << "clock_gettime(" << clk_id
<< ") failed.";
82 return base::TimeTicks();
86 (static_cast<int64
>(ts
.tv_sec
) * base::Time::kMicrosecondsPerSecond
) +
87 (static_cast<int64
>(ts
.tv_nsec
) / base::Time::kNanosecondsPerMicrosecond
);
89 return base::TimeTicks::FromInternalValue(absolute_micro
);
91 #else // _POSIX_MONOTONIC_CLOCK
92 #error No usable tick clock function on this platform.
93 #endif // _POSIX_MONOTONIC_CLOCK
94 #endif // !defined(OS_MACOSX)
100 struct timespec
TimeDelta::ToTimeSpec() const {
101 int64 microseconds
= InMicroseconds();
103 if (microseconds
>= Time::kMicrosecondsPerSecond
) {
104 seconds
= InSeconds();
105 microseconds
-= seconds
* Time::kMicrosecondsPerSecond
;
107 struct timespec result
=
109 static_cast<long>(microseconds
* Time::kNanosecondsPerMicrosecond
)};
113 #if !defined(OS_MACOSX)
114 // The Time routines in this file use standard POSIX routines, or almost-
115 // standard routines in the case of timegm. We need to use a Mach-specific
116 // function for TimeTicks::Now() on Mac OS X.
118 // Time -----------------------------------------------------------------------
120 // Windows uses a Gregorian epoch of 1601. We need to match this internally
121 // so that our time representations match across all platforms. See bug 14734.
122 // irb(main):010:0> Time.at(0).getutc()
123 // => Thu Jan 01 00:00:00 UTC 1970
124 // irb(main):011:0> Time.at(-11644473600).getutc()
125 // => Mon Jan 01 00:00:00 UTC 1601
126 static const int64 kWindowsEpochDeltaSeconds
= GG_INT64_C(11644473600);
127 static const int64 kWindowsEpochDeltaMilliseconds
=
128 kWindowsEpochDeltaSeconds
* Time::kMillisecondsPerSecond
;
131 const int64
Time::kWindowsEpochDeltaMicroseconds
=
132 kWindowsEpochDeltaSeconds
* Time::kMicrosecondsPerSecond
;
134 // Some functions in time.cc use time_t directly, so we provide an offset
135 // to convert from time_t (Unix epoch) and internal (Windows epoch).
137 const int64
Time::kTimeTToMicrosecondsOffset
= kWindowsEpochDeltaMicroseconds
;
142 struct timezone tz
= { 0, 0 }; // UTC
143 if (gettimeofday(&tv
, &tz
) != 0) {
144 DCHECK(0) << "Could not determine time of day";
145 LOG_ERRNO(ERROR
) << "Call to gettimeofday failed.";
146 // Return null instead of uninitialized |tv| value, which contains random
147 // garbage data. This may result in the crash seen in crbug.com/147570.
150 // Combine seconds and microseconds in a 64-bit field containing microseconds
151 // since the epoch. That's enough for nearly 600 centuries. Adjust from
152 // Unix (1970) to Windows (1601) epoch.
153 return Time((tv
.tv_sec
* kMicrosecondsPerSecond
+ tv
.tv_usec
) +
154 kWindowsEpochDeltaMicroseconds
);
158 Time
Time::NowFromSystemTime() {
159 // Just use Now() because Now() returns the system time.
163 void Time::Explode(bool is_local
, Exploded
* exploded
) const {
164 // Time stores times with microsecond resolution, but Exploded only carries
165 // millisecond resolution, so begin by being lossy. Adjust from Windows
166 // epoch (1601) to Unix epoch (1970);
167 int64 microseconds
= us_
- kWindowsEpochDeltaMicroseconds
;
168 // The following values are all rounded towards -infinity.
169 int64 milliseconds
; // Milliseconds since epoch.
170 SysTime seconds
; // Seconds since epoch.
171 int millisecond
; // Exploded millisecond value (0-999).
172 if (microseconds
>= 0) {
173 // Rounding towards -infinity <=> rounding towards 0, in this case.
174 milliseconds
= microseconds
/ kMicrosecondsPerMillisecond
;
175 seconds
= milliseconds
/ kMillisecondsPerSecond
;
176 millisecond
= milliseconds
% kMillisecondsPerSecond
;
178 // Round these *down* (towards -infinity).
179 milliseconds
= (microseconds
- kMicrosecondsPerMillisecond
+ 1) /
180 kMicrosecondsPerMillisecond
;
181 seconds
= (milliseconds
- kMillisecondsPerSecond
+ 1) /
182 kMillisecondsPerSecond
;
183 // Make this nonnegative (and between 0 and 999 inclusive).
184 millisecond
= milliseconds
% kMillisecondsPerSecond
;
186 millisecond
+= kMillisecondsPerSecond
;
189 struct tm timestruct
;
190 SysTimeToTimeStruct(seconds
, ×truct
, is_local
);
192 exploded
->year
= timestruct
.tm_year
+ 1900;
193 exploded
->month
= timestruct
.tm_mon
+ 1;
194 exploded
->day_of_week
= timestruct
.tm_wday
;
195 exploded
->day_of_month
= timestruct
.tm_mday
;
196 exploded
->hour
= timestruct
.tm_hour
;
197 exploded
->minute
= timestruct
.tm_min
;
198 exploded
->second
= timestruct
.tm_sec
;
199 exploded
->millisecond
= millisecond
;
203 Time
Time::FromExploded(bool is_local
, const Exploded
& exploded
) {
204 struct tm timestruct
;
205 timestruct
.tm_sec
= exploded
.second
;
206 timestruct
.tm_min
= exploded
.minute
;
207 timestruct
.tm_hour
= exploded
.hour
;
208 timestruct
.tm_mday
= exploded
.day_of_month
;
209 timestruct
.tm_mon
= exploded
.month
- 1;
210 timestruct
.tm_year
= exploded
.year
- 1900;
211 timestruct
.tm_wday
= exploded
.day_of_week
; // mktime/timegm ignore this
212 timestruct
.tm_yday
= 0; // mktime/timegm ignore this
213 timestruct
.tm_isdst
= -1; // attempt to figure it out
214 #if !defined(OS_NACL) && !defined(OS_SOLARIS)
215 timestruct
.tm_gmtoff
= 0; // not a POSIX field, so mktime/timegm ignore
216 timestruct
.tm_zone
= NULL
; // not a POSIX field, so mktime/timegm ignore
219 SysTime seconds
= SysTimeFromTimeStruct(×truct
, is_local
);
222 // Handle overflow. Clamping the range to what mktime and timegm might
223 // return is the best that can be done here. It's not ideal, but it's better
224 // than failing here or ignoring the overflow case and treating each time
225 // overflow as one second prior to the epoch.
227 (exploded
.year
< 1969 || exploded
.year
> 1970)) {
228 // If exploded.year is 1969 or 1970, take -1 as correct, with the
229 // time indicating 1 second prior to the epoch. (1970 is allowed to handle
230 // time zone and DST offsets.) Otherwise, return the most future or past
231 // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
233 // The minimum and maximum representible times that mktime and timegm could
234 // return are used here instead of values outside that range to allow for
235 // proper round-tripping between exploded and counter-type time
236 // representations in the presence of possible truncation to time_t by
237 // division and use with other functions that accept time_t.
239 // When representing the most distant time in the future, add in an extra
240 // 999ms to avoid the time being less than any other possible value that
241 // this function can return.
242 if (exploded
.year
< 1969) {
243 CHECK(sizeof(SysTime
) < sizeof(int64
)) << "integer overflow";
244 milliseconds
= std::numeric_limits
<SysTime
>::min();
245 milliseconds
*= kMillisecondsPerSecond
;
247 CHECK(sizeof(SysTime
) < sizeof(int64
)) << "integer overflow";
248 milliseconds
= std::numeric_limits
<SysTime
>::max();
249 milliseconds
*= kMillisecondsPerSecond
;
250 milliseconds
+= (kMillisecondsPerSecond
- 1);
253 milliseconds
= seconds
* kMillisecondsPerSecond
+ exploded
.millisecond
;
256 // Adjust from Unix (1970) to Windows (1601) epoch.
257 return Time((milliseconds
* kMicrosecondsPerMillisecond
) +
258 kWindowsEpochDeltaMicroseconds
);
261 // TimeTicks ------------------------------------------------------------------
263 TimeTicks
TimeTicks::Now() {
264 return ClockNow(CLOCK_MONOTONIC
);
268 TimeTicks
TimeTicks::HighResNow() {
273 TimeTicks
TimeTicks::ThreadNow() {
274 #if defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)
275 return ClockNow(CLOCK_THREAD_CPUTIME_ID
);
282 #if defined(OS_CHROMEOS)
283 // Force definition of the system trace clock; it is a chromeos-only api
284 // at the moment and surfacing it in the right place requires mucking
286 #define CLOCK_SYSTEM_TRACE 11
289 TimeTicks
TimeTicks::NowFromSystemTraceTime() {
290 uint64_t absolute_micro
;
293 if (clock_gettime(CLOCK_SYSTEM_TRACE
, &ts
) != 0) {
294 // NB: fall-back for a chrome os build running on linux
299 (static_cast<int64
>(ts
.tv_sec
) * Time::kMicrosecondsPerSecond
) +
300 (static_cast<int64
>(ts
.tv_nsec
) / Time::kNanosecondsPerMicrosecond
);
302 return TimeTicks(absolute_micro
);
305 #else // !defined(OS_CHROMEOS)
308 TimeTicks
TimeTicks::NowFromSystemTraceTime() {
312 #endif // defined(OS_CHROMEOS)
317 Time
Time::FromTimeVal(struct timeval t
) {
318 DCHECK_LT(t
.tv_usec
, static_cast<int>(Time::kMicrosecondsPerSecond
));
319 DCHECK_GE(t
.tv_usec
, 0);
320 if (t
.tv_usec
== 0 && t
.tv_sec
== 0)
322 if (t
.tv_usec
== static_cast<suseconds_t
>(Time::kMicrosecondsPerSecond
) - 1 &&
323 t
.tv_sec
== std::numeric_limits
<time_t>::max())
326 (static_cast<int64
>(t
.tv_sec
) * Time::kMicrosecondsPerSecond
) +
328 kTimeTToMicrosecondsOffset
);
331 struct timeval
Time::ToTimeVal() const {
332 struct timeval result
;
339 result
.tv_sec
= std::numeric_limits
<time_t>::max();
340 result
.tv_usec
= static_cast<suseconds_t
>(Time::kMicrosecondsPerSecond
) - 1;
343 int64 us
= us_
- kTimeTToMicrosecondsOffset
;
344 result
.tv_sec
= us
/ Time::kMicrosecondsPerSecond
;
345 result
.tv_usec
= us
% Time::kMicrosecondsPerSecond
;