blob: 0a2677838617e79ada4b219cc684631cf799a519 [file] [log] [blame]
avi@chromium.org1c519e92013-06-28 03:04:56 +09001// 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.
4
tnagel@chromium.org4c4f4112014-05-14 02:39:11 +09005// Time represents an absolute point in coordinated universal time (UTC),
6// internally represented as microseconds (s/1,000,000) since the Windows epoch
7// (1601-01-01 00:00:00 UTC) (See http://crbug.com/14734). System-dependent
8// clock interface routines are defined in time_PLATFORM.cc.
avi@chromium.org1c519e92013-06-28 03:04:56 +09009//
10// TimeDelta represents a duration of time, internally represented in
11// microseconds.
12//
13// TimeTicks represents an abstract time that is most of the time incrementing
14// for use in measuring time durations. It is internally represented in
15// microseconds. It can not be converted to a human-readable time, but is
16// guaranteed not to decrease (if the user changes the computer clock,
17// Time::Now() may actually decrease or jump). But note that TimeTicks may
18// "stand still", for example if the computer suspended.
19//
20// These classes are represented as only a 64-bit value, so they can be
21// efficiently passed by value.
ricea749c6422014-10-29 20:35:45 +090022//
23// Definitions of operator<< are provided to make these types work with
24// DCHECK_EQ() and other log macros. For human-readable formatting, see
25// "base/i18n/time_formatting.h".
avi@chromium.org1c519e92013-06-28 03:04:56 +090026
27#ifndef BASE_TIME_TIME_H_
28#define BASE_TIME_TIME_H_
29
30#include <time.h>
31
ricea749c6422014-10-29 20:35:45 +090032#include <iosfwd>
33
avi@chromium.org1c519e92013-06-28 03:04:56 +090034#include "base/base_export.h"
35#include "base/basictypes.h"
rvargas47e8f4c2015-03-21 16:41:21 +090036#include "base/numerics/safe_math.h"
mostynb@opera.comf29dd612013-09-04 08:29:12 +090037#include "build/build_config.h"
avi@chromium.org1c519e92013-06-28 03:04:56 +090038
39#if defined(OS_MACOSX)
40#include <CoreFoundation/CoreFoundation.h>
41// Avoid Mac system header macro leak.
42#undef TYPE_BOOL
43#endif
44
45#if defined(OS_POSIX)
ernstm@chromium.org9bad9a12013-07-31 15:36:04 +090046#include <unistd.h>
avi@chromium.org1c519e92013-06-28 03:04:56 +090047#include <sys/time.h>
48#endif
49
50#if defined(OS_WIN)
51// For FILETIME in FromFileTime, until it moves to a new converter class.
52// See TODO(iyengar) below.
53#include <windows.h>
54#endif
55
56#include <limits>
57
58namespace base {
59
miu352541f2015-05-10 09:15:21 +090060class TimeDelta;
61
62// The functions in the time_internal namespace are meant to be used only by the
63// time classes and functions. Please use the math operators defined in the
64// time classes instead.
65namespace time_internal {
66
67// Add or subtract |value| from a TimeDelta. The int64 argument and return value
68// are in terms of a microsecond timebase.
69BASE_EXPORT int64 SaturatedAdd(TimeDelta delta, int64 value);
70BASE_EXPORT int64 SaturatedSub(TimeDelta delta, int64 value);
71
72// Clamp |value| on overflow and underflow conditions. The int64 argument and
73// return value are in terms of a microsecond timebase.
74BASE_EXPORT int64 FromCheckedNumeric(const CheckedNumeric<int64> value);
75
76} // namespace time_internal
avi@chromium.org1c519e92013-06-28 03:04:56 +090077
78// TimeDelta ------------------------------------------------------------------
79
80class BASE_EXPORT TimeDelta {
81 public:
82 TimeDelta() : delta_(0) {
83 }
84
85 // Converts units of time to TimeDeltas.
gavinp@chromium.org096c1632014-03-06 05:02:05 +090086 static TimeDelta FromDays(int days);
87 static TimeDelta FromHours(int hours);
88 static TimeDelta FromMinutes(int minutes);
avi@chromium.org1c519e92013-06-28 03:04:56 +090089 static TimeDelta FromSeconds(int64 secs);
90 static TimeDelta FromMilliseconds(int64 ms);
behara.ms@samsung.com8c037ed2014-04-22 18:00:53 +090091 static TimeDelta FromSecondsD(double secs);
92 static TimeDelta FromMillisecondsD(double ms);
avi@chromium.org1c519e92013-06-28 03:04:56 +090093 static TimeDelta FromMicroseconds(int64 us);
94#if defined(OS_WIN)
95 static TimeDelta FromQPCValue(LONGLONG qpc_value);
96#endif
97
98 // Converts an integer value representing TimeDelta to a class. This is used
99 // when deserializing a |TimeDelta| structure, using a value known to be
100 // compatible. It is not provided as a constructor because the integer type
101 // may be unclear from the perspective of a caller.
102 static TimeDelta FromInternalValue(int64 delta) {
103 return TimeDelta(delta);
104 }
105
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900106 // Returns the maximum time delta, which should be greater than any reasonable
107 // time delta we might compare it to. Adding or subtracting the maximum time
108 // delta to a time or another time delta has an undefined result.
109 static TimeDelta Max();
110
avi@chromium.org1c519e92013-06-28 03:04:56 +0900111 // Returns the internal numeric value of the TimeDelta object. Please don't
112 // use this and do arithmetic on it, as it is more error prone than using the
113 // provided operators.
114 // For serializing, use FromInternalValue to reconstitute.
115 int64 ToInternalValue() const {
116 return delta_;
117 }
118
miuf8ef55b2015-01-14 14:33:08 +0900119 // Returns the magnitude (absolute value) of this TimeDelta.
120 TimeDelta magnitude() const {
121 // Some toolchains provide an incomplete C++11 implementation and lack an
122 // int64 overload for std::abs(). The following is a simple branchless
123 // implementation:
124 const int64 mask = delta_ >> (sizeof(delta_) * 8 - 1);
125 return TimeDelta((delta_ + mask) ^ mask);
126 }
127
miu352541f2015-05-10 09:15:21 +0900128 // Returns true if the time delta is zero.
129 bool is_zero() const {
130 return delta_ == 0;
131 }
132
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900133 // Returns true if the time delta is the maximum time delta.
134 bool is_max() const {
135 return delta_ == std::numeric_limits<int64>::max();
136 }
137
avi@chromium.org1c519e92013-06-28 03:04:56 +0900138#if defined(OS_POSIX)
139 struct timespec ToTimeSpec() const;
140#endif
141
142 // Returns the time delta in some unit. The F versions return a floating
143 // point value, the "regular" versions return a rounded-down value.
144 //
145 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
146 // to the next full millisecond.
147 int InDays() const;
148 int InHours() const;
149 int InMinutes() const;
150 double InSecondsF() const;
151 int64 InSeconds() const;
152 double InMillisecondsF() const;
153 int64 InMilliseconds() const;
154 int64 InMillisecondsRoundedUp() const;
155 int64 InMicroseconds() const;
156
157 TimeDelta& operator=(TimeDelta other) {
158 delta_ = other.delta_;
159 return *this;
160 }
161
162 // Computations with other deltas.
163 TimeDelta operator+(TimeDelta other) const {
miu352541f2015-05-10 09:15:21 +0900164 return TimeDelta(time_internal::SaturatedAdd(*this, other.delta_));
avi@chromium.org1c519e92013-06-28 03:04:56 +0900165 }
166 TimeDelta operator-(TimeDelta other) const {
miu352541f2015-05-10 09:15:21 +0900167 return TimeDelta(time_internal::SaturatedSub(*this, other.delta_));
avi@chromium.org1c519e92013-06-28 03:04:56 +0900168 }
169
170 TimeDelta& operator+=(TimeDelta other) {
miu352541f2015-05-10 09:15:21 +0900171 return *this = (*this + other);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900172 }
173 TimeDelta& operator-=(TimeDelta other) {
miu352541f2015-05-10 09:15:21 +0900174 return *this = (*this - other);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900175 }
176 TimeDelta operator-() const {
177 return TimeDelta(-delta_);
178 }
179
michaeln74a80192015-02-24 06:22:42 +0900180 // Computations with numeric types.
181 template<typename T>
182 TimeDelta operator*(T a) const {
rvargas47e8f4c2015-03-21 16:41:21 +0900183 CheckedNumeric<int64> rv(delta_);
184 rv *= a;
miu352541f2015-05-10 09:15:21 +0900185 return TimeDelta(time_internal::FromCheckedNumeric(rv));
avi@chromium.org1c519e92013-06-28 03:04:56 +0900186 }
michaeln74a80192015-02-24 06:22:42 +0900187 template<typename T>
188 TimeDelta operator/(T a) const {
rvargas47e8f4c2015-03-21 16:41:21 +0900189 CheckedNumeric<int64> rv(delta_);
190 rv /= a;
miu352541f2015-05-10 09:15:21 +0900191 return TimeDelta(time_internal::FromCheckedNumeric(rv));
avi@chromium.org1c519e92013-06-28 03:04:56 +0900192 }
michaeln74a80192015-02-24 06:22:42 +0900193 template<typename T>
194 TimeDelta& operator*=(T a) {
miu352541f2015-05-10 09:15:21 +0900195 return *this = (*this * a);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900196 }
michaeln74a80192015-02-24 06:22:42 +0900197 template<typename T>
198 TimeDelta& operator/=(T a) {
miu352541f2015-05-10 09:15:21 +0900199 return *this = (*this / a);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900200 }
michaeln74a80192015-02-24 06:22:42 +0900201
avi@chromium.org1c519e92013-06-28 03:04:56 +0900202 int64 operator/(TimeDelta a) const {
203 return delta_ / a.delta_;
204 }
miu352541f2015-05-10 09:15:21 +0900205 TimeDelta operator%(TimeDelta a) const {
206 return TimeDelta(delta_ % a.delta_);
207 }
avi@chromium.org1c519e92013-06-28 03:04:56 +0900208
209 // Comparison operators.
210 bool operator==(TimeDelta other) const {
211 return delta_ == other.delta_;
212 }
213 bool operator!=(TimeDelta other) const {
214 return delta_ != other.delta_;
215 }
216 bool operator<(TimeDelta other) const {
217 return delta_ < other.delta_;
218 }
219 bool operator<=(TimeDelta other) const {
220 return delta_ <= other.delta_;
221 }
222 bool operator>(TimeDelta other) const {
223 return delta_ > other.delta_;
224 }
225 bool operator>=(TimeDelta other) const {
226 return delta_ >= other.delta_;
227 }
228
229 private:
miu352541f2015-05-10 09:15:21 +0900230 friend int64 time_internal::SaturatedAdd(TimeDelta delta, int64 value);
231 friend int64 time_internal::SaturatedSub(TimeDelta delta, int64 value);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900232
233 // Constructs a delta given the duration in microseconds. This is private
234 // to avoid confusion by callers with an integer constructor. Use
235 // FromSeconds, FromMilliseconds, etc. instead.
236 explicit TimeDelta(int64 delta_us) : delta_(delta_us) {
237 }
238
239 // Delta in microseconds.
240 int64 delta_;
241};
242
michaeln74a80192015-02-24 06:22:42 +0900243template<typename T>
244inline TimeDelta operator*(T a, TimeDelta td) {
245 return td * a;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900246}
247
ricea749c6422014-10-29 20:35:45 +0900248// For logging use only.
249BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
250
miu352541f2015-05-10 09:15:21 +0900251// Do not reference the time_internal::TimeBase template class directly. Please
252// use one of the time subclasses instead, and only reference the public
253// TimeBase members via those classes.
254namespace time_internal {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900255
miu352541f2015-05-10 09:15:21 +0900256// TimeBase--------------------------------------------------------------------
257
258// Provides value storage and comparison/math operations common to all time
259// classes. Each subclass provides for strong type-checking to ensure
260// semantically meaningful comparison/math of time values from the same clock
261// source or timeline.
262template<class TimeClass>
263class TimeBase {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900264 public:
qiankun.miaoac3307a2015-03-17 15:52:53 +0900265 static const int64 kHoursPerDay = 24;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900266 static const int64 kMillisecondsPerSecond = 1000;
qiankun.miaoac3307a2015-03-17 15:52:53 +0900267 static const int64 kMillisecondsPerDay = kMillisecondsPerSecond * 60 * 60 *
268 kHoursPerDay;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900269 static const int64 kMicrosecondsPerMillisecond = 1000;
270 static const int64 kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
271 kMillisecondsPerSecond;
272 static const int64 kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
273 static const int64 kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
qiankun.miaoac3307a2015-03-17 15:52:53 +0900274 static const int64 kMicrosecondsPerDay = kMicrosecondsPerHour * kHoursPerDay;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900275 static const int64 kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
276 static const int64 kNanosecondsPerMicrosecond = 1000;
277 static const int64 kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
278 kMicrosecondsPerSecond;
279
miu352541f2015-05-10 09:15:21 +0900280 // Returns true if this object has not been initialized.
281 //
282 // Warning: Be careful when writing code that performs math on time values,
283 // since it's possible to produce a valid "zero" result that should not be
284 // interpreted as a "null" value.
285 bool is_null() const {
286 return us_ == 0;
287 }
288
289 // Returns true if this object represents the maximum time.
290 bool is_max() const {
291 return us_ == std::numeric_limits<int64>::max();
292 }
293
294 // For serializing only. Use FromInternalValue() to reconstitute. Please don't
295 // use this and do arithmetic on it, as it is more error prone than using the
296 // provided operators.
297 int64 ToInternalValue() const {
298 return us_;
299 }
300
301 TimeClass& operator=(TimeClass other) {
302 us_ = other.us_;
303 return *(static_cast<TimeClass*>(this));
304 }
305
306 // Compute the difference between two times.
307 TimeDelta operator-(TimeClass other) const {
308 return TimeDelta::FromMicroseconds(us_ - other.us_);
309 }
310
311 // Return a new time modified by some delta.
312 TimeClass operator+(TimeDelta delta) const {
313 return TimeClass(time_internal::SaturatedAdd(delta, us_));
314 }
315 TimeClass operator-(TimeDelta delta) const {
316 return TimeClass(-time_internal::SaturatedSub(delta, us_));
317 }
318
319 // Modify by some time delta.
320 TimeClass& operator+=(TimeDelta delta) {
321 return static_cast<TimeClass&>(*this = (*this + delta));
322 }
323 TimeClass& operator-=(TimeDelta delta) {
324 return static_cast<TimeClass&>(*this = (*this - delta));
325 }
326
327 // Comparison operators
328 bool operator==(TimeClass other) const {
329 return us_ == other.us_;
330 }
331 bool operator!=(TimeClass other) const {
332 return us_ != other.us_;
333 }
334 bool operator<(TimeClass other) const {
335 return us_ < other.us_;
336 }
337 bool operator<=(TimeClass other) const {
338 return us_ <= other.us_;
339 }
340 bool operator>(TimeClass other) const {
341 return us_ > other.us_;
342 }
343 bool operator>=(TimeClass other) const {
344 return us_ >= other.us_;
345 }
346
347 // Converts an integer value representing TimeClass to a class. This is used
348 // when deserializing a |TimeClass| structure, using a value known to be
349 // compatible. It is not provided as a constructor because the integer type
350 // may be unclear from the perspective of a caller.
351 static TimeClass FromInternalValue(int64 us) {
352 return TimeClass(us);
353 }
354
355 protected:
356 explicit TimeBase(int64 us) : us_(us) {
357 }
358
359 // Time value in a microsecond timebase.
360 int64 us_;
361};
362
363} // namespace time_internal
364
365template<class TimeClass>
366inline TimeClass operator+(TimeDelta delta, TimeClass t) {
367 return t + delta;
368}
369
370// Time -----------------------------------------------------------------------
371
372// Represents a wall clock time in UTC. Values are not guaranteed to be
373// monotonically non-decreasing and are subject to large amounts of skew.
374class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
375 public:
erikchen38dbe3d2014-11-12 11:57:56 +0900376 // The representation of Jan 1, 1970 UTC in microseconds since the
377 // platform-dependent epoch.
378 static const int64 kTimeTToMicrosecondsOffset;
379
avi@chromium.org1c519e92013-06-28 03:04:56 +0900380#if !defined(OS_WIN)
381 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
382 // the Posix delta of 1970. This is used for migrating between the old
383 // 1970-based epochs to the new 1601-based ones. It should be removed from
384 // this global header and put in the platform-specific ones when we remove the
385 // migration code.
386 static const int64 kWindowsEpochDeltaMicroseconds;
fmeawad@chromium.org074db922014-08-06 15:21:18 +0900387#else
388 // To avoid overflow in QPC to Microseconds calculations, since we multiply
389 // by kMicrosecondsPerSecond, then the QPC value should not exceed
390 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
391 static const int64 kQPCOverflowThreshold = 0x8637BD05AF7;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900392#endif
393
394 // Represents an exploded time that can be formatted nicely. This is kind of
395 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
396 // additions and changes to prevent errors.
397 struct BASE_EXPORT Exploded {
398 int year; // Four digit year "2007"
399 int month; // 1-based month (values 1 = January, etc.)
400 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
401 int day_of_month; // 1-based day of month (1-31)
402 int hour; // Hour within the current day (0-23)
403 int minute; // Minute within the current hour (0-59)
404 int second; // Second within the current minute (0-59 plus leap
405 // seconds which may take it up to 60).
406 int millisecond; // Milliseconds within the current second (0-999)
407
408 // A cursory test for whether the data members are within their
409 // respective ranges. A 'true' return value does not guarantee the
410 // Exploded value can be successfully converted to a Time value.
411 bool HasValidValues() const;
412 };
413
414 // Contains the NULL time. Use Time::Now() to get the current time.
miu352541f2015-05-10 09:15:21 +0900415 Time() : TimeBase(0) {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900416 }
417
418 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
419 static Time UnixEpoch();
420
421 // Returns the current time. Watch out, the system might adjust its clock
422 // in which case time will actually go backwards. We don't guarantee that
423 // times are increasing, or that two calls to Now() won't be the same.
424 static Time Now();
425
426 // Returns the maximum time, which should be greater than any reasonable time
427 // with which we might compare it.
428 static Time Max();
429
430 // Returns the current time. Same as Now() except that this function always
431 // uses system time so that there are no discrepancies between the returned
432 // time and system time even on virtual environments including our test bot.
433 // For timing sensitive unittests, this function should be used.
434 static Time NowFromSystemTime();
435
436 // Converts to/from time_t in UTC and a Time class.
437 // TODO(brettw) this should be removed once everybody starts using the |Time|
438 // class.
439 static Time FromTimeT(time_t tt);
440 time_t ToTimeT() const;
441
442 // Converts time to/from a double which is the number of seconds since epoch
443 // (Jan 1, 1970). Webkit uses this format to represent time.
444 // Because WebKit initializes double time value to 0 to indicate "not
445 // initialized", we map it to empty Time object that also means "not
446 // initialized".
447 static Time FromDoubleT(double dt);
448 double ToDoubleT() const;
449
450#if defined(OS_POSIX)
451 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
452 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
453 // having a 1 second resolution, which agrees with
454 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
455 static Time FromTimeSpec(const timespec& ts);
456#endif
457
458 // Converts to/from the Javascript convention for times, a number of
459 // milliseconds since the epoch:
460 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
461 static Time FromJsTime(double ms_since_epoch);
462 double ToJsTime() const;
463
apiccion@chromium.orgcaa7e462013-09-24 02:52:36 +0900464 // Converts to Java convention for times, a number of
465 // milliseconds since the epoch.
466 int64 ToJavaTime() const;
467
avi@chromium.org1c519e92013-06-28 03:04:56 +0900468#if defined(OS_POSIX)
469 static Time FromTimeVal(struct timeval t);
470 struct timeval ToTimeVal() const;
471#endif
472
473#if defined(OS_MACOSX)
474 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
475 CFAbsoluteTime ToCFAbsoluteTime() const;
476#endif
477
478#if defined(OS_WIN)
479 static Time FromFileTime(FILETIME ft);
480 FILETIME ToFileTime() const;
481
482 // The minimum time of a low resolution timer. This is basically a windows
483 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
484 // treat it as static across all windows versions.
485 static const int kMinLowResolutionThresholdMs = 16;
486
cpue9b293b2014-08-27 12:58:22 +0900487 // Enable or disable Windows high resolution timer.
avi@chromium.org1c519e92013-06-28 03:04:56 +0900488 static void EnableHighResolutionTimer(bool enable);
489
490 // Activates or deactivates the high resolution timer based on the |activate|
491 // flag. If the HighResolutionTimer is not Enabled (see
492 // EnableHighResolutionTimer), this function will return false. Otherwise
493 // returns true. Each successful activate call must be paired with a
494 // subsequent deactivate call.
495 // All callers to activate the high resolution timer must eventually call
496 // this function to deactivate the high resolution timer.
497 static bool ActivateHighResolutionTimer(bool activate);
498
499 // Returns true if the high resolution timer is both enabled and activated.
500 // This is provided for testing only, and is not tracked in a thread-safe
501 // way.
502 static bool IsHighResolutionTimerInUse();
503#endif
504
505 // Converts an exploded structure representing either the local time or UTC
506 // into a Time class.
507 static Time FromUTCExploded(const Exploded& exploded) {
508 return FromExploded(false, exploded);
509 }
510 static Time FromLocalExploded(const Exploded& exploded) {
511 return FromExploded(true, exploded);
512 }
513
avi@chromium.org1c519e92013-06-28 03:04:56 +0900514 // Converts a string representation of time to a Time object.
515 // An example of a time string which is converted is as below:-
516 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
517 // in the input string, FromString assumes local time and FromUTCString
518 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
519 // specified in RFC822) is treated as if the timezone is not specified.
520 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
521 // a new time converter class.
522 static bool FromString(const char* time_string, Time* parsed_time) {
523 return FromStringInternal(time_string, true, parsed_time);
524 }
525 static bool FromUTCString(const char* time_string, Time* parsed_time) {
526 return FromStringInternal(time_string, false, parsed_time);
527 }
528
avi@chromium.org1c519e92013-06-28 03:04:56 +0900529 // Fills the given exploded structure with either the local time or UTC from
530 // this time structure (containing UTC).
531 void UTCExplode(Exploded* exploded) const {
532 return Explode(false, exploded);
533 }
534 void LocalExplode(Exploded* exploded) const {
535 return Explode(true, exploded);
536 }
537
538 // Rounds this time down to the nearest day in local time. It will represent
539 // midnight on that day.
540 Time LocalMidnight() const;
541
gcastod3c5c102015-05-08 07:36:57 +0900542 private:
miu352541f2015-05-10 09:15:21 +0900543 friend class time_internal::TimeBase<Time>;
gcastod3c5c102015-05-08 07:36:57 +0900544
miu352541f2015-05-10 09:15:21 +0900545 explicit Time(int64 us) : TimeBase(us) {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900546 }
547
548 // Explodes the given time to either local time |is_local = true| or UTC
549 // |is_local = false|.
550 void Explode(bool is_local, Exploded* exploded) const;
551
552 // Unexplodes a given time assuming the source is either local time
553 // |is_local = true| or UTC |is_local = false|.
554 static Time FromExploded(bool is_local, const Exploded& exploded);
555
556 // Converts a string representation of time to a Time object.
557 // An example of a time string which is converted is as below:-
558 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
559 // in the input string, local time |is_local = true| or
560 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
561 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
562 // timezone is not specified.
563 static bool FromStringInternal(const char* time_string,
564 bool is_local,
565 Time* parsed_time);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900566};
567
568// Inline the TimeDelta factory methods, for fast TimeDelta construction.
569
570// static
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900571inline TimeDelta TimeDelta::FromDays(int days) {
572 // Preserve max to prevent overflow.
573 if (days == std::numeric_limits<int>::max())
574 return Max();
avi@chromium.org1c519e92013-06-28 03:04:56 +0900575 return TimeDelta(days * Time::kMicrosecondsPerDay);
576}
577
578// static
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900579inline TimeDelta TimeDelta::FromHours(int hours) {
580 // Preserve max to prevent overflow.
581 if (hours == std::numeric_limits<int>::max())
582 return Max();
avi@chromium.org1c519e92013-06-28 03:04:56 +0900583 return TimeDelta(hours * Time::kMicrosecondsPerHour);
584}
585
586// static
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900587inline TimeDelta TimeDelta::FromMinutes(int minutes) {
588 // Preserve max to prevent overflow.
589 if (minutes == std::numeric_limits<int>::max())
590 return Max();
avi@chromium.org1c519e92013-06-28 03:04:56 +0900591 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
592}
593
594// static
595inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900596 // Preserve max to prevent overflow.
597 if (secs == std::numeric_limits<int64>::max())
598 return Max();
avi@chromium.org1c519e92013-06-28 03:04:56 +0900599 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
600}
601
602// static
603inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900604 // Preserve max to prevent overflow.
605 if (ms == std::numeric_limits<int64>::max())
606 return Max();
avi@chromium.org1c519e92013-06-28 03:04:56 +0900607 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
608}
609
610// static
behara.ms@samsung.com8c037ed2014-04-22 18:00:53 +0900611inline TimeDelta TimeDelta::FromSecondsD(double secs) {
612 // Preserve max to prevent overflow.
613 if (secs == std::numeric_limits<double>::infinity())
614 return Max();
pkasting9043c4e2014-10-02 07:18:43 +0900615 return TimeDelta(static_cast<int64>(secs * Time::kMicrosecondsPerSecond));
behara.ms@samsung.com8c037ed2014-04-22 18:00:53 +0900616}
617
618// static
619inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
620 // Preserve max to prevent overflow.
621 if (ms == std::numeric_limits<double>::infinity())
622 return Max();
pkasting9043c4e2014-10-02 07:18:43 +0900623 return TimeDelta(static_cast<int64>(ms * Time::kMicrosecondsPerMillisecond));
behara.ms@samsung.com8c037ed2014-04-22 18:00:53 +0900624}
625
626// static
avi@chromium.org1c519e92013-06-28 03:04:56 +0900627inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900628 // Preserve max to prevent overflow.
629 if (us == std::numeric_limits<int64>::max())
630 return Max();
avi@chromium.org1c519e92013-06-28 03:04:56 +0900631 return TimeDelta(us);
632}
633
ricea749c6422014-10-29 20:35:45 +0900634// For logging use only.
635BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
636
avi@chromium.org1c519e92013-06-28 03:04:56 +0900637// TimeTicks ------------------------------------------------------------------
638
miu352541f2015-05-10 09:15:21 +0900639// Represents monotonically non-decreasing clock time.
640class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900641 public:
hamaji@chromium.org1332a212014-06-06 15:02:05 +0900642 // We define this even without OS_CHROMEOS for seccomp sandbox testing.
643#if defined(OS_LINUX)
644 // Force definition of the system trace clock; it is a chromeos-only api
645 // at the moment and surfacing it in the right place requires mucking
646 // with glibc et al.
647 static const clockid_t kClockSystemTrace = 11;
648#endif
649
miu352541f2015-05-10 09:15:21 +0900650 TimeTicks() : TimeBase(0) {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900651 }
652
miuf8ef55b2015-01-14 14:33:08 +0900653 // Platform-dependent tick count representing "right now." When
654 // IsHighResolution() returns false, the resolution of the clock could be
655 // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
656 // microsecond.
avi@chromium.org1c519e92013-06-28 03:04:56 +0900657 static TimeTicks Now();
658
miuf8ef55b2015-01-14 14:33:08 +0900659 // Returns true if the high resolution clock is working on this system and
660 // Now() will return high resolution values. Note that, on systems where the
661 // high resolution clock works but is deemed inefficient, the low resolution
662 // clock will be used instead.
663 static bool IsHighResolution();
664
ernstm@chromium.org9bad9a12013-07-31 15:36:04 +0900665 // Returns true if ThreadNow() is supported on this system.
666 static bool IsThreadNowSupported() {
fmeawad@chromium.org292d1e82013-11-07 10:01:46 +0900667#if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
fmeawad@chromium.orgac55aa42013-11-12 15:12:38 +0900668 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
ernstm@chromium.org9bad9a12013-07-31 15:36:04 +0900669 return true;
670#else
671 return false;
672#endif
673 }
674
675 // Returns thread-specific CPU-time on systems that support this feature.
676 // Needs to be guarded with a call to IsThreadNowSupported(). Use this timer
677 // to (approximately) measure how much time the calling thread spent doing
678 // actual work vs. being de-scheduled. May return bogus results if the thread
679 // migrates to another CPU between two calls.
miuf8ef55b2015-01-14 14:33:08 +0900680 //
681 // WARNING: The returned value might NOT have the same origin as Now(). Do not
682 // perform math between TimeTicks values returned by Now() and ThreadNow() and
683 // expect meaningful results.
684 // TODO(miu): Since the timeline of these values is different, the values
685 // should be of a different type.
ernstm@chromium.org9bad9a12013-07-31 15:36:04 +0900686 static TimeTicks ThreadNow();
687
miuf8ef55b2015-01-14 14:33:08 +0900688 // Returns the current system trace time or, if not available on this
689 // platform, a high-resolution time value; or a low-resolution time value if
690 // neither are avalable. On systems where a global trace clock is defined,
691 // timestamping TraceEvents's with this value guarantees synchronization
692 // between events collected inside chrome and events collected outside
693 // (e.g. kernel, X server).
694 //
695 // WARNING: The returned value might NOT have the same origin as Now(). Do not
696 // perform math between TimeTicks values returned by Now() and
697 // NowFromSystemTraceTime() and expect meaningful results.
698 // TODO(miu): Since the timeline of these values is different, the values
699 // should be of a different type.
avi@chromium.org1c519e92013-06-28 03:04:56 +0900700 static TimeTicks NowFromSystemTraceTime();
701
702#if defined(OS_WIN)
miuf8ef55b2015-01-14 14:33:08 +0900703 // Translates an absolute QPC timestamp into a TimeTicks value. The returned
704 // value has the same origin as Now(). Do NOT attempt to use this if
705 // IsHighResolution() returns false.
avi@chromium.org1c519e92013-06-28 03:04:56 +0900706 static TimeTicks FromQPCValue(LONGLONG qpc_value);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900707#endif
708
pwestin@google.come5211132013-11-01 05:29:38 +0900709 // Get the TimeTick value at the time of the UnixEpoch. This is useful when
710 // you need to relate the value of TimeTicks to a real time and date.
711 // Note: Upon first invocation, this function takes a snapshot of the realtime
712 // clock to establish a reference point. This function will return the same
713 // value for the duration of the application, but will be different in future
714 // application runs.
715 static TimeTicks UnixEpoch();
716
briandersone3dd73e2015-02-13 09:06:08 +0900717 // Returns |this| snapped to the next tick, given a |tick_phase| and
718 // repeating |tick_interval| in both directions. |this| may be before,
719 // after, or equal to the |tick_phase|.
720 TimeTicks SnappedToNextTick(TimeTicks tick_phase,
721 TimeDelta tick_interval) const;
722
gcastod3c5c102015-05-08 07:36:57 +0900723#if defined(OS_WIN)
miu352541f2015-05-10 09:15:21 +0900724 protected:
avi@chromium.org1c519e92013-06-28 03:04:56 +0900725 typedef DWORD (*TickFunctionType)(void);
726 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
727#endif
ksakamotof75c6812015-05-07 13:35:19 +0900728
miu352541f2015-05-10 09:15:21 +0900729 private:
730 friend class time_internal::TimeBase<TimeTicks>;
731
732 // Please use Now() to create a new object. This is for internal use
733 // and testing.
734 explicit TimeTicks(int64 us) : TimeBase(us) {
735 }
736};
gcastod3c5c102015-05-08 07:36:57 +0900737
ricea749c6422014-10-29 20:35:45 +0900738// For logging use only.
739BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
740
avi@chromium.org1c519e92013-06-28 03:04:56 +0900741} // namespace base
742
743#endif // BASE_TIME_TIME_H_