blob: 9456cc7513c13727b87a9decd5837d65e9e5a912 [file] [log] [blame]
Vitaly Bukacbed2062015-08-17 12:54:05 -07001// 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
5// 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). 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.
12//
13// TimeDelta represents a duration of time, internally represented in
14// microseconds.
15//
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080016// 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.
Vitaly Bukacbed2062015-08-17 12:54:05 -070023//
24// 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).
27//
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".
31//
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.
Vitaly Bukacbed2062015-08-17 12:54:05 -070048
49#ifndef BASE_TIME_TIME_H_
50#define BASE_TIME_TIME_H_
51
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080052#include <stdint.h>
Vitaly Bukacbed2062015-08-17 12:54:05 -070053#include <time.h>
54
55#include <iosfwd>
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080056#include <limits>
Vitaly Bukacbed2062015-08-17 12:54:05 -070057
58#include "base/base_export.h"
Vitaly Bukacbed2062015-08-17 12:54:05 -070059#include "base/numerics/safe_math.h"
Alex Vakulenkof1fa8be2015-12-08 12:38:56 -080060#include "build/build_config.h"
Vitaly Bukacbed2062015-08-17 12:54:05 -070061
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)
69#include <unistd.h>
70#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>
Vitaly Bukacbed2062015-08-17 12:54:05 -070077
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080078#include "base/gtest_prod_util.h"
79#endif
Vitaly Bukacbed2062015-08-17 12:54:05 -070080
81namespace base {
82
83class 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
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080090// 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);
Vitaly Bukacbed2062015-08-17 12:54:05 -070094
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080095// Clamp |value| on overflow and underflow conditions. The int64_t argument and
Vitaly Bukacbed2062015-08-17 12:54:05 -070096// return value are in terms of a microsecond timebase.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080097BASE_EXPORT int64_t FromCheckedNumeric(const CheckedNumeric<int64_t> value);
Vitaly Bukacbed2062015-08-17 12:54:05 -070098
99} // namespace time_internal
100
101// TimeDelta ------------------------------------------------------------------
102
103class BASE_EXPORT TimeDelta {
104 public:
105 TimeDelta() : delta_(0) {
106 }
107
108 // Converts units of time to TimeDeltas.
109 static TimeDelta FromDays(int days);
110 static TimeDelta FromHours(int hours);
111 static TimeDelta FromMinutes(int minutes);
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800112 static TimeDelta FromSeconds(int64_t secs);
113 static TimeDelta FromMilliseconds(int64_t ms);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700114 static TimeDelta FromSecondsD(double secs);
115 static TimeDelta FromMillisecondsD(double ms);
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800116 static TimeDelta FromMicroseconds(int64_t us);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700117#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.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800125 static TimeDelta FromInternalValue(int64_t delta) { return TimeDelta(delta); }
Vitaly Bukacbed2062015-08-17 12:54:05 -0700126
127 // 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
132 // 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.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800136 int64_t ToInternalValue() const { return delta_; }
Vitaly Bukacbed2062015-08-17 12:54:05 -0700137
138 // Returns the magnitude (absolute value) of this TimeDelta.
139 TimeDelta magnitude() const {
140 // Some toolchains provide an incomplete C++11 implementation and lack an
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800141 // int64_t overload for std::abs(). The following is a simple branchless
Vitaly Bukacbed2062015-08-17 12:54:05 -0700142 // implementation:
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800143 const int64_t mask = delta_ >> (sizeof(delta_) * 8 - 1);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700144 return TimeDelta((delta_ + mask) ^ mask);
145 }
146
147 // Returns true if the time delta is zero.
148 bool is_zero() const {
149 return delta_ == 0;
150 }
151
152 // Returns true if the time delta is the maximum time delta.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800153 bool is_max() const { return delta_ == std::numeric_limits<int64_t>::max(); }
Vitaly Bukacbed2062015-08-17 12:54:05 -0700154
155#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;
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800168 int64_t InSeconds() const;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700169 double InMillisecondsF() const;
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800170 int64_t InMilliseconds() const;
171 int64_t InMillisecondsRoundedUp() const;
172 int64_t InMicroseconds() const;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700173
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 {
181 return TimeDelta(time_internal::SaturatedAdd(*this, other.delta_));
182 }
183 TimeDelta operator-(TimeDelta other) const {
184 return TimeDelta(time_internal::SaturatedSub(*this, other.delta_));
185 }
186
187 TimeDelta& operator+=(TimeDelta other) {
188 return *this = (*this + other);
189 }
190 TimeDelta& operator-=(TimeDelta other) {
191 return *this = (*this - other);
192 }
193 TimeDelta operator-() const {
194 return TimeDelta(-delta_);
195 }
196
197 // Computations with numeric types.
198 template<typename T>
199 TimeDelta operator*(T a) const {
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800200 CheckedNumeric<int64_t> rv(delta_);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700201 rv *= a;
202 return TimeDelta(time_internal::FromCheckedNumeric(rv));
203 }
204 template<typename T>
205 TimeDelta operator/(T a) const {
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800206 CheckedNumeric<int64_t> rv(delta_);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700207 rv /= a;
208 return TimeDelta(time_internal::FromCheckedNumeric(rv));
209 }
210 template<typename T>
211 TimeDelta& operator*=(T a) {
212 return *this = (*this * a);
213 }
214 template<typename T>
215 TimeDelta& operator/=(T a) {
216 return *this = (*this / a);
217 }
218
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800219 int64_t operator/(TimeDelta a) const { return delta_ / a.delta_; }
Vitaly Bukacbed2062015-08-17 12:54:05 -0700220 TimeDelta operator%(TimeDelta a) const {
221 return TimeDelta(delta_ % a.delta_);
222 }
223
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:
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800245 friend int64_t time_internal::SaturatedAdd(TimeDelta delta, int64_t value);
246 friend int64_t time_internal::SaturatedSub(TimeDelta delta, int64_t value);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700247
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.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800251 explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {}
252
253 // Private method to build a delta from a double.
254 static TimeDelta FromDouble(double value);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700255
256 // Delta in microseconds.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800257 int64_t delta_;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700258};
259
260template<typename T>
261inline TimeDelta operator*(T a, TimeDelta td) {
262 return td * a;
263}
264
265// For logging use only.
266BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
267
268// 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 {
272
273// 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 {
281 public:
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800282 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;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700297
298 // 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.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800308 bool is_max() const { return us_ == std::numeric_limits<int64_t>::max(); }
Vitaly Bukacbed2062015-08-17 12:54:05 -0700309
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.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800313 int64_t ToInternalValue() const { return us_; }
Vitaly Bukacbed2062015-08-17 12:54:05 -0700314
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.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800365 static TimeClass FromInternalValue(int64_t us) { return TimeClass(us); }
Vitaly Bukacbed2062015-08-17 12:54:05 -0700366
367 protected:
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800368 explicit TimeBase(int64_t us) : us_(us) {}
Vitaly Bukacbed2062015-08-17 12:54:05 -0700369
370 // Time value in a microsecond timebase.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800371 int64_t us_;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700372};
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:
387 // The representation of Jan 1, 1970 UTC in microseconds since the
388 // platform-dependent epoch.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800389 static const int64_t kTimeTToMicrosecondsOffset;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700390
391#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.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800397 static const int64_t kWindowsEpochDeltaMicroseconds;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700398#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.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800402 enum : int64_t{kQPCOverflowThreshold = 0x8637BD05AF7};
Vitaly Bukacbed2062015-08-17 12:54:05 -0700403#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.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700408 struct Exploded {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700409 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.
426 Time() : TimeBase(0) {
427 }
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
475 // Converts to Java convention for times, a number of
476 // milliseconds since the epoch.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800477 int64_t ToJavaTime() const;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700478
479#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
498 // Enable or disable Windows high resolution timer.
499 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
Vitaly Bukacbed2062015-08-17 12:54:05 -0700525 // Fills the given exploded structure with either the local time or UTC from
526 // this time structure (containing UTC).
527 void UTCExplode(Exploded* exploded) const {
528 return Explode(false, exploded);
529 }
530 void LocalExplode(Exploded* exploded) const {
531 return Explode(true, exploded);
532 }
533
534 // Rounds this time down to the nearest day in local time. It will represent
535 // midnight on that day.
536 Time LocalMidnight() const;
537
538 private:
539 friend class time_internal::TimeBase<Time>;
540
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800541 explicit Time(int64_t us) : TimeBase(us) {}
Vitaly Bukacbed2062015-08-17 12:54:05 -0700542
543 // Explodes the given time to either local time |is_local = true| or UTC
544 // |is_local = false|.
545 void Explode(bool is_local, Exploded* exploded) const;
546
547 // Unexplodes a given time assuming the source is either local time
548 // |is_local = true| or UTC |is_local = false|.
549 static Time FromExploded(bool is_local, const Exploded& exploded);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700550};
551
552// Inline the TimeDelta factory methods, for fast TimeDelta construction.
553
554// static
555inline TimeDelta TimeDelta::FromDays(int days) {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700556 if (days == std::numeric_limits<int>::max())
557 return Max();
558 return TimeDelta(days * Time::kMicrosecondsPerDay);
559}
560
561// static
562inline TimeDelta TimeDelta::FromHours(int hours) {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700563 if (hours == std::numeric_limits<int>::max())
564 return Max();
565 return TimeDelta(hours * Time::kMicrosecondsPerHour);
566}
567
568// static
569inline TimeDelta TimeDelta::FromMinutes(int minutes) {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700570 if (minutes == std::numeric_limits<int>::max())
571 return Max();
572 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
573}
574
575// static
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800576inline TimeDelta TimeDelta::FromSeconds(int64_t secs) {
577 return TimeDelta(secs) * Time::kMicrosecondsPerSecond;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700578}
579
580// static
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800581inline TimeDelta TimeDelta::FromMilliseconds(int64_t ms) {
582 return TimeDelta(ms) * Time::kMicrosecondsPerMillisecond;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700583}
584
585// static
586inline TimeDelta TimeDelta::FromSecondsD(double secs) {
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800587 return FromDouble(secs * Time::kMicrosecondsPerSecond);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700588}
589
590// static
591inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800592 return FromDouble(ms * Time::kMicrosecondsPerMillisecond);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700593}
594
595// static
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800596inline TimeDelta TimeDelta::FromMicroseconds(int64_t us) {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700597 return TimeDelta(us);
598}
599
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800600// static
601inline TimeDelta TimeDelta::FromDouble(double value) {
602 double max_magnitude = std::numeric_limits<int64_t>::max();
603 TimeDelta delta = TimeDelta(static_cast<int64_t>(value));
604 if (value > max_magnitude)
605 delta = Max();
606 else if (value < -max_magnitude)
607 delta = -Max();
608 return delta;
609}
610
Vitaly Bukacbed2062015-08-17 12:54:05 -0700611// For logging use only.
612BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
613
614// TimeTicks ------------------------------------------------------------------
615
616// Represents monotonically non-decreasing clock time.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700617class TimeTicks : public time_internal::TimeBase<TimeTicks> {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700618 public:
619 TimeTicks() : TimeBase(0) {
620 }
621
622 // Platform-dependent tick count representing "right now." When
623 // IsHighResolution() returns false, the resolution of the clock could be
624 // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
625 // microsecond.
626 static TimeTicks Now();
627
628 // Returns true if the high resolution clock is working on this system and
629 // Now() will return high resolution values. Note that, on systems where the
630 // high resolution clock works but is deemed inefficient, the low resolution
631 // clock will be used instead.
632 static bool IsHighResolution();
633
634#if defined(OS_WIN)
635 // Translates an absolute QPC timestamp into a TimeTicks value. The returned
636 // value has the same origin as Now(). Do NOT attempt to use this if
637 // IsHighResolution() returns false.
638 static TimeTicks FromQPCValue(LONGLONG qpc_value);
639#endif
640
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800641 // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because
642 // Time and TimeTicks respond differently to user-set time and NTP
643 // adjustments, this number is only an estimate. Nevertheless, this can be
644 // useful when you need to relate the value of TimeTicks to a real time and
645 // date. Note: Upon first invocation, this function takes a snapshot of the
646 // realtime clock to establish a reference point. This function will return
647 // the same value for the duration of the application, but will be different
648 // in future application runs.
Vitaly Bukacbed2062015-08-17 12:54:05 -0700649 static TimeTicks UnixEpoch();
650
651 // Returns |this| snapped to the next tick, given a |tick_phase| and
652 // repeating |tick_interval| in both directions. |this| may be before,
653 // after, or equal to the |tick_phase|.
654 TimeTicks SnappedToNextTick(TimeTicks tick_phase,
655 TimeDelta tick_interval) const;
656
657#if defined(OS_WIN)
658 protected:
659 typedef DWORD (*TickFunctionType)(void);
660 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
661#endif
662
663 private:
664 friend class time_internal::TimeBase<TimeTicks>;
665
666 // Please use Now() to create a new object. This is for internal use
667 // and testing.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800668 explicit TimeTicks(int64_t us) : TimeBase(us) {}
Vitaly Bukacbed2062015-08-17 12:54:05 -0700669};
670
671// For logging use only.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700672std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700673
674// ThreadTicks ----------------------------------------------------------------
675
676// Represents a clock, specific to a particular thread, than runs only while the
677// thread is running.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700678class ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700679 public:
680 ThreadTicks() : TimeBase(0) {
681 }
682
683 // Returns true if ThreadTicks::Now() is supported on this system.
684 static bool IsSupported() {
685#if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
686 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
687 return true;
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800688#elif defined(OS_WIN)
689 return IsSupportedWin();
Vitaly Bukacbed2062015-08-17 12:54:05 -0700690#else
691 return false;
692#endif
693 }
694
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800695 // Waits until the initialization is completed. Needs to be guarded with a
696 // call to IsSupported().
697 static void WaitUntilInitialized() {
698#if defined(OS_WIN)
699 WaitUntilInitializedWin();
700#endif
701 }
702
Vitaly Bukacbed2062015-08-17 12:54:05 -0700703 // Returns thread-specific CPU-time on systems that support this feature.
704 // Needs to be guarded with a call to IsSupported(). Use this timer
705 // to (approximately) measure how much time the calling thread spent doing
706 // actual work vs. being de-scheduled. May return bogus results if the thread
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800707 // migrates to another CPU between two calls. Returns an empty ThreadTicks
708 // object until the initialization is completed. If a clock reading is
709 // absolutely needed, call WaitUntilInitialized() before this method.
Vitaly Bukacbed2062015-08-17 12:54:05 -0700710 static ThreadTicks Now();
711
712 private:
713 friend class time_internal::TimeBase<ThreadTicks>;
714
715 // Please use Now() to create a new object. This is for internal use
716 // and testing.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800717 explicit ThreadTicks(int64_t us) : TimeBase(us) {}
718
Vitaly Bukacbed2062015-08-17 12:54:05 -0700719};
720
721// For logging use only.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700722std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700723
Vitaly Bukacbed2062015-08-17 12:54:05 -0700724} // namespace base
725
726#endif // BASE_TIME_TIME_H_