blob: 1989dbf8f27758e0643a3732859bcb62aca672c2 [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
miu85c35562015-05-30 08:57:12 +09007// (1601-01-01 00:00:00 UTC). System-dependent clock interface routines are
8// defined in time_PLATFORM.cc. Note that values for Time may skew and jump
9// around as the operating system makes adjustments to synchronize (e.g., with
10// NTP servers). Thus, client code that uses the Time class must account for
11// this.
avi@chromium.org1c519e92013-06-28 03:04:56 +090012//
13// TimeDelta represents a duration of time, internally represented in
14// microseconds.
15//
charliea1cd12102015-11-05 22:48:56 +090016// TimeTicks and ThreadTicks represent an abstract time that is most of the time
17// incrementing, for use in measuring time durations. Internally, they are
18// represented in microseconds. They can not be converted to a human-readable
19// time, but are guaranteed not to decrease (unlike the Time class). Note that
20// TimeTicks may "stand still" (e.g., if the computer is suspended), and
21// ThreadTicks will "stand still" whenever the thread has been de-scheduled by
22// the operating system.
avi@chromium.org1c519e92013-06-28 03:04:56 +090023//
miu85c35562015-05-30 08:57:12 +090024// All time classes are copyable, assignable, and occupy 64-bits per
25// instance. Thus, they can be efficiently passed by-value (as opposed to
26// by-reference).
ricea749c6422014-10-29 20:35:45 +090027//
28// Definitions of operator<< are provided to make these types work with
29// DCHECK_EQ() and other log macros. For human-readable formatting, see
30// "base/i18n/time_formatting.h".
miu85c35562015-05-30 08:57:12 +090031//
32// So many choices! Which time class should you use? Examples:
33//
34// Time: Interpreting the wall-clock time provided by a remote
35// system. Detecting whether cached resources have
36// expired. Providing the user with a display of the current date
37// and time. Determining the amount of time between events across
38// re-boots of the machine.
39//
40// TimeTicks: Tracking the amount of time a task runs. Executing delayed
41// tasks at the right time. Computing presentation timestamps.
42// Synchronizing audio and video using TimeTicks as a common
43// reference clock (lip-sync). Measuring network round-trip
44// latency.
45//
46// ThreadTicks: Benchmarking how long the current thread has been doing actual
47// work.
avi@chromium.org1c519e92013-06-28 03:04:56 +090048
49#ifndef BASE_TIME_TIME_H_
50#define BASE_TIME_TIME_H_
51
avia6a6a682015-12-27 07:15:14 +090052#include <stdint.h>
avi@chromium.org1c519e92013-06-28 03:04:56 +090053#include <time.h>
54
ricea749c6422014-10-29 20:35:45 +090055#include <iosfwd>
avia6a6a682015-12-27 07:15:14 +090056#include <limits>
ricea749c6422014-10-29 20:35:45 +090057
avi@chromium.org1c519e92013-06-28 03:04:56 +090058#include "base/base_export.h"
rvargas47e8f4c2015-03-21 16:41:21 +090059#include "base/numerics/safe_math.h"
mostynb@opera.comf29dd612013-09-04 08:29:12 +090060#include "build/build_config.h"
avi@chromium.org1c519e92013-06-28 03:04:56 +090061
62#if defined(OS_MACOSX)
63#include <CoreFoundation/CoreFoundation.h>
64// Avoid Mac system header macro leak.
65#undef TYPE_BOOL
66#endif
67
68#if defined(OS_POSIX)
ernstm@chromium.org9bad9a12013-07-31 15:36:04 +090069#include <unistd.h>
avi@chromium.org1c519e92013-06-28 03:04:56 +090070#include <sys/time.h>
71#endif
72
73#if defined(OS_WIN)
74// For FILETIME in FromFileTime, until it moves to a new converter class.
75// See TODO(iyengar) below.
76#include <windows.h>
fdorayeabadbd2015-10-15 12:46:40 +090077
78#include "base/gtest_prod_util.h"
avi@chromium.org1c519e92013-06-28 03:04:56 +090079#endif
80
avi@chromium.org1c519e92013-06-28 03:04:56 +090081namespace base {
82
miu352541f2015-05-10 09:15:21 +090083class TimeDelta;
84
85// The functions in the time_internal namespace are meant to be used only by the
86// time classes and functions. Please use the math operators defined in the
87// time classes instead.
88namespace time_internal {
89
avia6a6a682015-12-27 07:15:14 +090090// Add or subtract |value| from a TimeDelta. The int64_t argument and return
91// value are in terms of a microsecond timebase.
92BASE_EXPORT int64_t SaturatedAdd(TimeDelta delta, int64_t value);
93BASE_EXPORT int64_t SaturatedSub(TimeDelta delta, int64_t value);
miu352541f2015-05-10 09:15:21 +090094
avia6a6a682015-12-27 07:15:14 +090095// Clamp |value| on overflow and underflow conditions. The int64_t argument and
miu352541f2015-05-10 09:15:21 +090096// return value are in terms of a microsecond timebase.
avia6a6a682015-12-27 07:15:14 +090097BASE_EXPORT int64_t FromCheckedNumeric(const CheckedNumeric<int64_t> value);
miu352541f2015-05-10 09:15:21 +090098
99} // namespace time_internal
avi@chromium.org1c519e92013-06-28 03:04:56 +0900100
101// TimeDelta ------------------------------------------------------------------
102
103class BASE_EXPORT TimeDelta {
104 public:
105 TimeDelta() : delta_(0) {
106 }
107
108 // Converts units of time to TimeDeltas.
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900109 static TimeDelta FromDays(int days);
110 static TimeDelta FromHours(int hours);
111 static TimeDelta FromMinutes(int minutes);
avia6a6a682015-12-27 07:15:14 +0900112 static TimeDelta FromSeconds(int64_t secs);
113 static TimeDelta FromMilliseconds(int64_t ms);
behara.ms@samsung.com8c037ed2014-04-22 18:00:53 +0900114 static TimeDelta FromSecondsD(double secs);
115 static TimeDelta FromMillisecondsD(double ms);
avia6a6a682015-12-27 07:15:14 +0900116 static TimeDelta FromMicroseconds(int64_t us);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900117#if defined(OS_WIN)
118 static TimeDelta FromQPCValue(LONGLONG qpc_value);
119#endif
120
121 // Converts an integer value representing TimeDelta to a class. This is used
122 // when deserializing a |TimeDelta| structure, using a value known to be
123 // compatible. It is not provided as a constructor because the integer type
124 // may be unclear from the perspective of a caller.
avia6a6a682015-12-27 07:15:14 +0900125 static TimeDelta FromInternalValue(int64_t delta) { return TimeDelta(delta); }
avi@chromium.org1c519e92013-06-28 03:04:56 +0900126
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900127 // Returns the maximum time delta, which should be greater than any reasonable
128 // time delta we might compare it to. Adding or subtracting the maximum time
129 // delta to a time or another time delta has an undefined result.
130 static TimeDelta Max();
131
avi@chromium.org1c519e92013-06-28 03:04:56 +0900132 // Returns the internal numeric value of the TimeDelta object. Please don't
133 // use this and do arithmetic on it, as it is more error prone than using the
134 // provided operators.
135 // For serializing, use FromInternalValue to reconstitute.
avia6a6a682015-12-27 07:15:14 +0900136 int64_t ToInternalValue() const { return delta_; }
avi@chromium.org1c519e92013-06-28 03:04:56 +0900137
miuf8ef55b2015-01-14 14:33:08 +0900138 // Returns the magnitude (absolute value) of this TimeDelta.
139 TimeDelta magnitude() const {
140 // Some toolchains provide an incomplete C++11 implementation and lack an
avia6a6a682015-12-27 07:15:14 +0900141 // int64_t overload for std::abs(). The following is a simple branchless
miuf8ef55b2015-01-14 14:33:08 +0900142 // implementation:
avia6a6a682015-12-27 07:15:14 +0900143 const int64_t mask = delta_ >> (sizeof(delta_) * 8 - 1);
miuf8ef55b2015-01-14 14:33:08 +0900144 return TimeDelta((delta_ + mask) ^ mask);
145 }
146
miu352541f2015-05-10 09:15:21 +0900147 // Returns true if the time delta is zero.
148 bool is_zero() const {
149 return delta_ == 0;
150 }
151
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900152 // Returns true if the time delta is the maximum time delta.
avia6a6a682015-12-27 07:15:14 +0900153 bool is_max() const { return delta_ == std::numeric_limits<int64_t>::max(); }
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900154
avi@chromium.org1c519e92013-06-28 03:04:56 +0900155#if defined(OS_POSIX)
156 struct timespec ToTimeSpec() const;
157#endif
158
159 // Returns the time delta in some unit. The F versions return a floating
160 // point value, the "regular" versions return a rounded-down value.
161 //
162 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
163 // to the next full millisecond.
164 int InDays() const;
165 int InHours() const;
166 int InMinutes() const;
167 double InSecondsF() const;
avia6a6a682015-12-27 07:15:14 +0900168 int64_t InSeconds() const;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900169 double InMillisecondsF() const;
avia6a6a682015-12-27 07:15:14 +0900170 int64_t InMilliseconds() const;
171 int64_t InMillisecondsRoundedUp() const;
172 int64_t InMicroseconds() const;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900173
174 TimeDelta& operator=(TimeDelta other) {
175 delta_ = other.delta_;
176 return *this;
177 }
178
179 // Computations with other deltas.
180 TimeDelta operator+(TimeDelta other) const {
miu352541f2015-05-10 09:15:21 +0900181 return TimeDelta(time_internal::SaturatedAdd(*this, other.delta_));
avi@chromium.org1c519e92013-06-28 03:04:56 +0900182 }
183 TimeDelta operator-(TimeDelta other) const {
miu352541f2015-05-10 09:15:21 +0900184 return TimeDelta(time_internal::SaturatedSub(*this, other.delta_));
avi@chromium.org1c519e92013-06-28 03:04:56 +0900185 }
186
187 TimeDelta& operator+=(TimeDelta other) {
miu352541f2015-05-10 09:15:21 +0900188 return *this = (*this + other);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900189 }
190 TimeDelta& operator-=(TimeDelta other) {
miu352541f2015-05-10 09:15:21 +0900191 return *this = (*this - other);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900192 }
193 TimeDelta operator-() const {
194 return TimeDelta(-delta_);
195 }
196
michaeln74a80192015-02-24 06:22:42 +0900197 // Computations with numeric types.
198 template<typename T>
199 TimeDelta operator*(T a) const {
avia6a6a682015-12-27 07:15:14 +0900200 CheckedNumeric<int64_t> rv(delta_);
rvargas47e8f4c2015-03-21 16:41:21 +0900201 rv *= a;
miu352541f2015-05-10 09:15:21 +0900202 return TimeDelta(time_internal::FromCheckedNumeric(rv));
avi@chromium.org1c519e92013-06-28 03:04:56 +0900203 }
michaeln74a80192015-02-24 06:22:42 +0900204 template<typename T>
205 TimeDelta operator/(T a) const {
avia6a6a682015-12-27 07:15:14 +0900206 CheckedNumeric<int64_t> rv(delta_);
rvargas47e8f4c2015-03-21 16:41:21 +0900207 rv /= a;
miu352541f2015-05-10 09:15:21 +0900208 return TimeDelta(time_internal::FromCheckedNumeric(rv));
avi@chromium.org1c519e92013-06-28 03:04:56 +0900209 }
michaeln74a80192015-02-24 06:22:42 +0900210 template<typename T>
211 TimeDelta& operator*=(T a) {
miu352541f2015-05-10 09:15:21 +0900212 return *this = (*this * a);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900213 }
michaeln74a80192015-02-24 06:22:42 +0900214 template<typename T>
215 TimeDelta& operator/=(T a) {
miu352541f2015-05-10 09:15:21 +0900216 return *this = (*this / a);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900217 }
michaeln74a80192015-02-24 06:22:42 +0900218
avia6a6a682015-12-27 07:15:14 +0900219 int64_t operator/(TimeDelta a) const { return delta_ / a.delta_; }
miu352541f2015-05-10 09:15:21 +0900220 TimeDelta operator%(TimeDelta a) const {
221 return TimeDelta(delta_ % a.delta_);
222 }
avi@chromium.org1c519e92013-06-28 03:04:56 +0900223
224 // Comparison operators.
225 bool operator==(TimeDelta other) const {
226 return delta_ == other.delta_;
227 }
228 bool operator!=(TimeDelta other) const {
229 return delta_ != other.delta_;
230 }
231 bool operator<(TimeDelta other) const {
232 return delta_ < other.delta_;
233 }
234 bool operator<=(TimeDelta other) const {
235 return delta_ <= other.delta_;
236 }
237 bool operator>(TimeDelta other) const {
238 return delta_ > other.delta_;
239 }
240 bool operator>=(TimeDelta other) const {
241 return delta_ >= other.delta_;
242 }
243
244 private:
avia6a6a682015-12-27 07:15:14 +0900245 friend int64_t time_internal::SaturatedAdd(TimeDelta delta, int64_t value);
246 friend int64_t time_internal::SaturatedSub(TimeDelta delta, int64_t value);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900247
248 // Constructs a delta given the duration in microseconds. This is private
249 // to avoid confusion by callers with an integer constructor. Use
250 // FromSeconds, FromMilliseconds, etc. instead.
avia6a6a682015-12-27 07:15:14 +0900251 explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {}
avi@chromium.org1c519e92013-06-28 03:04:56 +0900252
rvargas7505c4f2015-07-28 05:09:02 +0900253 // Private method to build a delta from a double.
254 static TimeDelta FromDouble(double value);
255
avi@chromium.org1c519e92013-06-28 03:04:56 +0900256 // Delta in microseconds.
avia6a6a682015-12-27 07:15:14 +0900257 int64_t delta_;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900258};
259
michaeln74a80192015-02-24 06:22:42 +0900260template<typename T>
261inline TimeDelta operator*(T a, TimeDelta td) {
262 return td * a;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900263}
264
ricea749c6422014-10-29 20:35:45 +0900265// For logging use only.
266BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
267
miu352541f2015-05-10 09:15:21 +0900268// Do not reference the time_internal::TimeBase template class directly. Please
269// use one of the time subclasses instead, and only reference the public
270// TimeBase members via those classes.
271namespace time_internal {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900272
miu352541f2015-05-10 09:15:21 +0900273// TimeBase--------------------------------------------------------------------
274
275// Provides value storage and comparison/math operations common to all time
276// classes. Each subclass provides for strong type-checking to ensure
277// semantically meaningful comparison/math of time values from the same clock
278// source or timeline.
279template<class TimeClass>
280class TimeBase {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900281 public:
avia6a6a682015-12-27 07:15:14 +0900282 static const int64_t kHoursPerDay = 24;
283 static const int64_t kMillisecondsPerSecond = 1000;
284 static const int64_t kMillisecondsPerDay =
285 kMillisecondsPerSecond * 60 * 60 * kHoursPerDay;
286 static const int64_t kMicrosecondsPerMillisecond = 1000;
287 static const int64_t kMicrosecondsPerSecond =
288 kMicrosecondsPerMillisecond * kMillisecondsPerSecond;
289 static const int64_t kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
290 static const int64_t kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
291 static const int64_t kMicrosecondsPerDay =
292 kMicrosecondsPerHour * kHoursPerDay;
293 static const int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
294 static const int64_t kNanosecondsPerMicrosecond = 1000;
295 static const int64_t kNanosecondsPerSecond =
296 kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900297
miu352541f2015-05-10 09:15:21 +0900298 // Returns true if this object has not been initialized.
299 //
300 // Warning: Be careful when writing code that performs math on time values,
301 // since it's possible to produce a valid "zero" result that should not be
302 // interpreted as a "null" value.
303 bool is_null() const {
304 return us_ == 0;
305 }
306
307 // Returns true if this object represents the maximum time.
avia6a6a682015-12-27 07:15:14 +0900308 bool is_max() const { return us_ == std::numeric_limits<int64_t>::max(); }
miu352541f2015-05-10 09:15:21 +0900309
310 // For serializing only. Use FromInternalValue() to reconstitute. Please don't
311 // use this and do arithmetic on it, as it is more error prone than using the
312 // provided operators.
avia6a6a682015-12-27 07:15:14 +0900313 int64_t ToInternalValue() const { return us_; }
miu352541f2015-05-10 09:15:21 +0900314
315 TimeClass& operator=(TimeClass other) {
316 us_ = other.us_;
317 return *(static_cast<TimeClass*>(this));
318 }
319
320 // Compute the difference between two times.
321 TimeDelta operator-(TimeClass other) const {
322 return TimeDelta::FromMicroseconds(us_ - other.us_);
323 }
324
325 // Return a new time modified by some delta.
326 TimeClass operator+(TimeDelta delta) const {
327 return TimeClass(time_internal::SaturatedAdd(delta, us_));
328 }
329 TimeClass operator-(TimeDelta delta) const {
330 return TimeClass(-time_internal::SaturatedSub(delta, us_));
331 }
332
333 // Modify by some time delta.
334 TimeClass& operator+=(TimeDelta delta) {
335 return static_cast<TimeClass&>(*this = (*this + delta));
336 }
337 TimeClass& operator-=(TimeDelta delta) {
338 return static_cast<TimeClass&>(*this = (*this - delta));
339 }
340
341 // Comparison operators
342 bool operator==(TimeClass other) const {
343 return us_ == other.us_;
344 }
345 bool operator!=(TimeClass other) const {
346 return us_ != other.us_;
347 }
348 bool operator<(TimeClass other) const {
349 return us_ < other.us_;
350 }
351 bool operator<=(TimeClass other) const {
352 return us_ <= other.us_;
353 }
354 bool operator>(TimeClass other) const {
355 return us_ > other.us_;
356 }
357 bool operator>=(TimeClass other) const {
358 return us_ >= other.us_;
359 }
360
361 // Converts an integer value representing TimeClass to a class. This is used
362 // when deserializing a |TimeClass| structure, using a value known to be
363 // compatible. It is not provided as a constructor because the integer type
364 // may be unclear from the perspective of a caller.
avia6a6a682015-12-27 07:15:14 +0900365 static TimeClass FromInternalValue(int64_t us) { return TimeClass(us); }
miu352541f2015-05-10 09:15:21 +0900366
367 protected:
avia6a6a682015-12-27 07:15:14 +0900368 explicit TimeBase(int64_t us) : us_(us) {}
miu352541f2015-05-10 09:15:21 +0900369
370 // Time value in a microsecond timebase.
avia6a6a682015-12-27 07:15:14 +0900371 int64_t us_;
miu352541f2015-05-10 09:15:21 +0900372};
373
374} // namespace time_internal
375
376template<class TimeClass>
377inline TimeClass operator+(TimeDelta delta, TimeClass t) {
378 return t + delta;
379}
380
381// Time -----------------------------------------------------------------------
382
383// Represents a wall clock time in UTC. Values are not guaranteed to be
384// monotonically non-decreasing and are subject to large amounts of skew.
385class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
386 public:
erikchen38dbe3d2014-11-12 11:57:56 +0900387 // The representation of Jan 1, 1970 UTC in microseconds since the
388 // platform-dependent epoch.
avia6a6a682015-12-27 07:15:14 +0900389 static const int64_t kTimeTToMicrosecondsOffset;
erikchen38dbe3d2014-11-12 11:57:56 +0900390
avi@chromium.org1c519e92013-06-28 03:04:56 +0900391#if !defined(OS_WIN)
392 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
393 // the Posix delta of 1970. This is used for migrating between the old
394 // 1970-based epochs to the new 1601-based ones. It should be removed from
395 // this global header and put in the platform-specific ones when we remove the
396 // migration code.
avia6a6a682015-12-27 07:15:14 +0900397 static const int64_t kWindowsEpochDeltaMicroseconds;
fmeawad@chromium.org074db922014-08-06 15:21:18 +0900398#else
399 // To avoid overflow in QPC to Microseconds calculations, since we multiply
400 // by kMicrosecondsPerSecond, then the QPC value should not exceed
401 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
avia6a6a682015-12-27 07:15:14 +0900402 enum : int64_t{kQPCOverflowThreshold = 0x8637BD05AF7};
avi@chromium.org1c519e92013-06-28 03:04:56 +0900403#endif
404
405 // Represents an exploded time that can be formatted nicely. This is kind of
406 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
407 // additions and changes to prevent errors.
408 struct BASE_EXPORT Exploded {
409 int year; // Four digit year "2007"
410 int month; // 1-based month (values 1 = January, etc.)
411 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
412 int day_of_month; // 1-based day of month (1-31)
413 int hour; // Hour within the current day (0-23)
414 int minute; // Minute within the current hour (0-59)
415 int second; // Second within the current minute (0-59 plus leap
416 // seconds which may take it up to 60).
417 int millisecond; // Milliseconds within the current second (0-999)
418
419 // A cursory test for whether the data members are within their
420 // respective ranges. A 'true' return value does not guarantee the
421 // Exploded value can be successfully converted to a Time value.
422 bool HasValidValues() const;
423 };
424
425 // Contains the NULL time. Use Time::Now() to get the current time.
miu352541f2015-05-10 09:15:21 +0900426 Time() : TimeBase(0) {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900427 }
428
429 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
430 static Time UnixEpoch();
431
432 // Returns the current time. Watch out, the system might adjust its clock
433 // in which case time will actually go backwards. We don't guarantee that
434 // times are increasing, or that two calls to Now() won't be the same.
435 static Time Now();
436
437 // Returns the maximum time, which should be greater than any reasonable time
438 // with which we might compare it.
439 static Time Max();
440
441 // Returns the current time. Same as Now() except that this function always
442 // uses system time so that there are no discrepancies between the returned
443 // time and system time even on virtual environments including our test bot.
444 // For timing sensitive unittests, this function should be used.
445 static Time NowFromSystemTime();
446
447 // Converts to/from time_t in UTC and a Time class.
448 // TODO(brettw) this should be removed once everybody starts using the |Time|
449 // class.
450 static Time FromTimeT(time_t tt);
451 time_t ToTimeT() const;
452
453 // Converts time to/from a double which is the number of seconds since epoch
454 // (Jan 1, 1970). Webkit uses this format to represent time.
455 // Because WebKit initializes double time value to 0 to indicate "not
456 // initialized", we map it to empty Time object that also means "not
457 // initialized".
458 static Time FromDoubleT(double dt);
459 double ToDoubleT() const;
460
461#if defined(OS_POSIX)
462 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
463 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
464 // having a 1 second resolution, which agrees with
465 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
466 static Time FromTimeSpec(const timespec& ts);
467#endif
468
469 // Converts to/from the Javascript convention for times, a number of
470 // milliseconds since the epoch:
471 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
472 static Time FromJsTime(double ms_since_epoch);
473 double ToJsTime() const;
474
apiccion@chromium.orgcaa7e462013-09-24 02:52:36 +0900475 // Converts to Java convention for times, a number of
476 // milliseconds since the epoch.
avia6a6a682015-12-27 07:15:14 +0900477 int64_t ToJavaTime() const;
apiccion@chromium.orgcaa7e462013-09-24 02:52:36 +0900478
avi@chromium.org1c519e92013-06-28 03:04:56 +0900479#if defined(OS_POSIX)
480 static Time FromTimeVal(struct timeval t);
481 struct timeval ToTimeVal() const;
482#endif
483
484#if defined(OS_MACOSX)
485 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
486 CFAbsoluteTime ToCFAbsoluteTime() const;
487#endif
488
489#if defined(OS_WIN)
490 static Time FromFileTime(FILETIME ft);
491 FILETIME ToFileTime() const;
492
493 // The minimum time of a low resolution timer. This is basically a windows
494 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
495 // treat it as static across all windows versions.
496 static const int kMinLowResolutionThresholdMs = 16;
497
cpue9b293b2014-08-27 12:58:22 +0900498 // Enable or disable Windows high resolution timer.
avi@chromium.org1c519e92013-06-28 03:04:56 +0900499 static void EnableHighResolutionTimer(bool enable);
500
501 // Activates or deactivates the high resolution timer based on the |activate|
502 // flag. If the HighResolutionTimer is not Enabled (see
503 // EnableHighResolutionTimer), this function will return false. Otherwise
504 // returns true. Each successful activate call must be paired with a
505 // subsequent deactivate call.
506 // All callers to activate the high resolution timer must eventually call
507 // this function to deactivate the high resolution timer.
508 static bool ActivateHighResolutionTimer(bool activate);
509
510 // Returns true if the high resolution timer is both enabled and activated.
511 // This is provided for testing only, and is not tracked in a thread-safe
512 // way.
513 static bool IsHighResolutionTimerInUse();
514#endif
515
516 // Converts an exploded structure representing either the local time or UTC
517 // into a Time class.
518 static Time FromUTCExploded(const Exploded& exploded) {
519 return FromExploded(false, exploded);
520 }
521 static Time FromLocalExploded(const Exploded& exploded) {
522 return FromExploded(true, exploded);
523 }
524
avi@chromium.org1c519e92013-06-28 03:04:56 +0900525 // Converts a string representation of time to a Time object.
526 // An example of a time string which is converted is as below:-
527 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
528 // in the input string, FromString assumes local time and FromUTCString
529 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
530 // specified in RFC822) is treated as if the timezone is not specified.
531 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
532 // a new time converter class.
533 static bool FromString(const char* time_string, Time* parsed_time) {
534 return FromStringInternal(time_string, true, parsed_time);
535 }
536 static bool FromUTCString(const char* time_string, Time* parsed_time) {
537 return FromStringInternal(time_string, false, parsed_time);
538 }
539
avi@chromium.org1c519e92013-06-28 03:04:56 +0900540 // Fills the given exploded structure with either the local time or UTC from
541 // this time structure (containing UTC).
542 void UTCExplode(Exploded* exploded) const {
543 return Explode(false, exploded);
544 }
545 void LocalExplode(Exploded* exploded) const {
546 return Explode(true, exploded);
547 }
548
549 // Rounds this time down to the nearest day in local time. It will represent
550 // midnight on that day.
551 Time LocalMidnight() const;
552
gcastod3c5c102015-05-08 07:36:57 +0900553 private:
miu352541f2015-05-10 09:15:21 +0900554 friend class time_internal::TimeBase<Time>;
gcastod3c5c102015-05-08 07:36:57 +0900555
avia6a6a682015-12-27 07:15:14 +0900556 explicit Time(int64_t us) : TimeBase(us) {}
avi@chromium.org1c519e92013-06-28 03:04:56 +0900557
558 // Explodes the given time to either local time |is_local = true| or UTC
559 // |is_local = false|.
560 void Explode(bool is_local, Exploded* exploded) const;
561
562 // Unexplodes a given time assuming the source is either local time
563 // |is_local = true| or UTC |is_local = false|.
564 static Time FromExploded(bool is_local, const Exploded& exploded);
565
566 // Converts a string representation of time to a Time object.
567 // An example of a time string which is converted is as below:-
568 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
569 // in the input string, local time |is_local = true| or
570 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
571 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
572 // timezone is not specified.
573 static bool FromStringInternal(const char* time_string,
574 bool is_local,
575 Time* parsed_time);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900576};
577
578// Inline the TimeDelta factory methods, for fast TimeDelta construction.
579
580// static
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900581inline TimeDelta TimeDelta::FromDays(int days) {
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900582 if (days == std::numeric_limits<int>::max())
583 return Max();
avi@chromium.org1c519e92013-06-28 03:04:56 +0900584 return TimeDelta(days * Time::kMicrosecondsPerDay);
585}
586
587// static
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900588inline TimeDelta TimeDelta::FromHours(int hours) {
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900589 if (hours == std::numeric_limits<int>::max())
590 return Max();
avi@chromium.org1c519e92013-06-28 03:04:56 +0900591 return TimeDelta(hours * Time::kMicrosecondsPerHour);
592}
593
594// static
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900595inline TimeDelta TimeDelta::FromMinutes(int minutes) {
gavinp@chromium.org096c1632014-03-06 05:02:05 +0900596 if (minutes == std::numeric_limits<int>::max())
597 return Max();
avi@chromium.org1c519e92013-06-28 03:04:56 +0900598 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
599}
600
601// static
avia6a6a682015-12-27 07:15:14 +0900602inline TimeDelta TimeDelta::FromSeconds(int64_t secs) {
rvargas7505c4f2015-07-28 05:09:02 +0900603 return TimeDelta(secs) * Time::kMicrosecondsPerSecond;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900604}
605
606// static
avia6a6a682015-12-27 07:15:14 +0900607inline TimeDelta TimeDelta::FromMilliseconds(int64_t ms) {
rvargas7505c4f2015-07-28 05:09:02 +0900608 return TimeDelta(ms) * Time::kMicrosecondsPerMillisecond;
avi@chromium.org1c519e92013-06-28 03:04:56 +0900609}
610
611// static
behara.ms@samsung.com8c037ed2014-04-22 18:00:53 +0900612inline TimeDelta TimeDelta::FromSecondsD(double secs) {
rvargas7505c4f2015-07-28 05:09:02 +0900613 return FromDouble(secs * Time::kMicrosecondsPerSecond);
behara.ms@samsung.com8c037ed2014-04-22 18:00:53 +0900614}
615
616// static
617inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
rvargas7505c4f2015-07-28 05:09:02 +0900618 return FromDouble(ms * Time::kMicrosecondsPerMillisecond);
behara.ms@samsung.com8c037ed2014-04-22 18:00:53 +0900619}
620
621// static
avia6a6a682015-12-27 07:15:14 +0900622inline TimeDelta TimeDelta::FromMicroseconds(int64_t us) {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900623 return TimeDelta(us);
624}
625
rvargas7505c4f2015-07-28 05:09:02 +0900626// static
627inline TimeDelta TimeDelta::FromDouble(double value) {
avia6a6a682015-12-27 07:15:14 +0900628 double max_magnitude = std::numeric_limits<int64_t>::max();
629 TimeDelta delta = TimeDelta(static_cast<int64_t>(value));
rvargas7505c4f2015-07-28 05:09:02 +0900630 if (value > max_magnitude)
631 delta = Max();
632 else if (value < -max_magnitude)
633 delta = -Max();
634 return delta;
635}
636
ricea749c6422014-10-29 20:35:45 +0900637// For logging use only.
638BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
639
avi@chromium.org1c519e92013-06-28 03:04:56 +0900640// TimeTicks ------------------------------------------------------------------
641
miu352541f2015-05-10 09:15:21 +0900642// Represents monotonically non-decreasing clock time.
643class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900644 public:
charliea908ce4d2016-04-01 04:05:18 +0900645 // The underlying clock used to generate new TimeTicks.
646 enum class Clock {
647 LINUX_CLOCK_MONOTONIC,
648 IOS_CF_ABSOLUTE_TIME_MINUS_KERN_BOOTTIME,
649 MAC_MACH_ABSOLUTE_TIME,
650 WIN_QPC,
651 WIN_ROLLOVER_PROTECTED_TIME_GET_TIME
652 };
653
miu352541f2015-05-10 09:15:21 +0900654 TimeTicks() : TimeBase(0) {
avi@chromium.org1c519e92013-06-28 03:04:56 +0900655 }
656
miuf8ef55b2015-01-14 14:33:08 +0900657 // Platform-dependent tick count representing "right now." When
658 // IsHighResolution() returns false, the resolution of the clock could be
659 // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
660 // microsecond.
avi@chromium.org1c519e92013-06-28 03:04:56 +0900661 static TimeTicks Now();
662
miuf8ef55b2015-01-14 14:33:08 +0900663 // Returns true if the high resolution clock is working on this system and
664 // Now() will return high resolution values. Note that, on systems where the
665 // high resolution clock works but is deemed inefficient, the low resolution
666 // clock will be used instead.
667 static bool IsHighResolution();
668
avi@chromium.org1c519e92013-06-28 03:04:56 +0900669#if defined(OS_WIN)
miuf8ef55b2015-01-14 14:33:08 +0900670 // Translates an absolute QPC timestamp into a TimeTicks value. The returned
671 // value has the same origin as Now(). Do NOT attempt to use this if
672 // IsHighResolution() returns false.
avi@chromium.org1c519e92013-06-28 03:04:56 +0900673 static TimeTicks FromQPCValue(LONGLONG qpc_value);
avi@chromium.org1c519e92013-06-28 03:04:56 +0900674#endif
675
charliea8290eef2015-10-08 06:46:23 +0900676 // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because
677 // Time and TimeTicks respond differently to user-set time and NTP
678 // adjustments, this number is only an estimate. Nevertheless, this can be
679 // useful when you need to relate the value of TimeTicks to a real time and
680 // date. Note: Upon first invocation, this function takes a snapshot of the
681 // realtime clock to establish a reference point. This function will return
682 // the same value for the duration of the application, but will be different
683 // in future application runs.
pwestin@google.come5211132013-11-01 05:29:38 +0900684 static TimeTicks UnixEpoch();
685
briandersone3dd73e2015-02-13 09:06:08 +0900686 // Returns |this| snapped to the next tick, given a |tick_phase| and
687 // repeating |tick_interval| in both directions. |this| may be before,
688 // after, or equal to the |tick_phase|.
689 TimeTicks SnappedToNextTick(TimeTicks tick_phase,
690 TimeDelta tick_interval) const;
691
charliea908ce4d2016-04-01 04:05:18 +0900692 // Returns an enum indicating the underlying clock being used to generate
693 // TimeTicks timestamps. This function should only be used for debugging and
694 // logging purposes.
695 static Clock GetClock();
696
gcastod3c5c102015-05-08 07:36:57 +0900697#if defined(OS_WIN)
miu352541f2015-05-10 09:15:21 +0900698 protected:
avi@chromium.org1c519e92013-06-28 03:04:56 +0900699 typedef DWORD (*TickFunctionType)(void);
700 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
701#endif
ksakamotof75c6812015-05-07 13:35:19 +0900702
miu352541f2015-05-10 09:15:21 +0900703 private:
704 friend class time_internal::TimeBase<TimeTicks>;
705
706 // Please use Now() to create a new object. This is for internal use
707 // and testing.
avia6a6a682015-12-27 07:15:14 +0900708 explicit TimeTicks(int64_t us) : TimeBase(us) {}
miu352541f2015-05-10 09:15:21 +0900709};
gcastod3c5c102015-05-08 07:36:57 +0900710
ricea749c6422014-10-29 20:35:45 +0900711// For logging use only.
712BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
713
miu85c35562015-05-30 08:57:12 +0900714// ThreadTicks ----------------------------------------------------------------
715
716// Represents a clock, specific to a particular thread, than runs only while the
717// thread is running.
718class BASE_EXPORT ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
719 public:
720 ThreadTicks() : TimeBase(0) {
721 }
722
723 // Returns true if ThreadTicks::Now() is supported on this system.
724 static bool IsSupported() {
725#if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
726 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
727 return true;
fdorayeabadbd2015-10-15 12:46:40 +0900728#elif defined(OS_WIN)
729 return IsSupportedWin();
miu85c35562015-05-30 08:57:12 +0900730#else
731 return false;
732#endif
733 }
734
fdorayeabadbd2015-10-15 12:46:40 +0900735 // Waits until the initialization is completed. Needs to be guarded with a
736 // call to IsSupported().
737 static void WaitUntilInitialized() {
738#if defined(OS_WIN)
739 WaitUntilInitializedWin();
740#endif
741 }
742
miu85c35562015-05-30 08:57:12 +0900743 // Returns thread-specific CPU-time on systems that support this feature.
744 // Needs to be guarded with a call to IsSupported(). Use this timer
745 // to (approximately) measure how much time the calling thread spent doing
746 // actual work vs. being de-scheduled. May return bogus results if the thread
fdorayeabadbd2015-10-15 12:46:40 +0900747 // migrates to another CPU between two calls. Returns an empty ThreadTicks
748 // object until the initialization is completed. If a clock reading is
749 // absolutely needed, call WaitUntilInitialized() before this method.
miu85c35562015-05-30 08:57:12 +0900750 static ThreadTicks Now();
751
752 private:
753 friend class time_internal::TimeBase<ThreadTicks>;
754
755 // Please use Now() to create a new object. This is for internal use
756 // and testing.
avia6a6a682015-12-27 07:15:14 +0900757 explicit ThreadTicks(int64_t us) : TimeBase(us) {}
fdorayeabadbd2015-10-15 12:46:40 +0900758
759#if defined(OS_WIN)
760 FRIEND_TEST_ALL_PREFIXES(TimeTicks, TSCTicksPerSecond);
761
762 // Returns the frequency of the TSC in ticks per second, or 0 if it hasn't
763 // been measured yet. Needs to be guarded with a call to IsSupported().
764 // This method is declared here rather than in the anonymous namespace to
765 // allow testing.
766 static double TSCTicksPerSecond();
767
768 static bool IsSupportedWin();
769 static void WaitUntilInitializedWin();
770#endif
miu85c35562015-05-30 08:57:12 +0900771};
772
773// For logging use only.
774BASE_EXPORT std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
775
avi@chromium.org1c519e92013-06-28 03:04:56 +0900776} // namespace base
777
778#endif // BASE_TIME_TIME_H_