blob: 1fe1b8563f60bba458bd67c7dd67a5cdd5ee78cf [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//
16// TimeTicks, ThreadTicks, and TraceTicks represent an abstract time that is
17// most of the time incrementing, for use in measuring time durations.
18// Internally, they are represented in microseconds. They can not be converted
19// to a human-readable time, but are guaranteed not to decrease (unlike the Time
20// class). Note that TimeTicks may "stand still" (e.g., if the computer is
21// suspended), and ThreadTicks will "stand still" whenever the thread has been
22// de-scheduled by the operating system.
23//
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.
48//
49// TraceTicks: This is only meant to be used by the event tracing
50// infrastructure, and by outside code modules in special
51// circumstances. Please be sure to consult a
52// base/trace_event/OWNER before committing any new code that
53// uses this.
54
55#ifndef BASE_TIME_TIME_H_
56#define BASE_TIME_TIME_H_
57
58#include <time.h>
59
60#include <iosfwd>
61
62#include "base/base_export.h"
63#include "base/basictypes.h"
64#include "base/numerics/safe_math.h"
Alex Vakulenkof1fa8be2015-12-08 12:38:56 -080065#include "build/build_config.h"
Vitaly Bukacbed2062015-08-17 12:54:05 -070066
67#if defined(OS_MACOSX)
68#include <CoreFoundation/CoreFoundation.h>
69// Avoid Mac system header macro leak.
70#undef TYPE_BOOL
71#endif
72
73#if defined(OS_POSIX)
74#include <unistd.h>
75#include <sys/time.h>
76#endif
77
78#if defined(OS_WIN)
79// For FILETIME in FromFileTime, until it moves to a new converter class.
80// See TODO(iyengar) below.
81#include <windows.h>
82#endif
83
84#include <limits>
85
86namespace base {
87
88class TimeDelta;
89
90// The functions in the time_internal namespace are meant to be used only by the
91// time classes and functions. Please use the math operators defined in the
92// time classes instead.
93namespace time_internal {
94
95// Add or subtract |value| from a TimeDelta. The int64 argument and return value
96// are in terms of a microsecond timebase.
97BASE_EXPORT int64 SaturatedAdd(TimeDelta delta, int64 value);
98BASE_EXPORT int64 SaturatedSub(TimeDelta delta, int64 value);
99
100// Clamp |value| on overflow and underflow conditions. The int64 argument and
101// return value are in terms of a microsecond timebase.
102BASE_EXPORT int64 FromCheckedNumeric(const CheckedNumeric<int64> value);
103
104} // namespace time_internal
105
106// TimeDelta ------------------------------------------------------------------
107
108class BASE_EXPORT TimeDelta {
109 public:
110 TimeDelta() : delta_(0) {
111 }
112
113 // Converts units of time to TimeDeltas.
114 static TimeDelta FromDays(int days);
115 static TimeDelta FromHours(int hours);
116 static TimeDelta FromMinutes(int minutes);
117 static TimeDelta FromSeconds(int64 secs);
118 static TimeDelta FromMilliseconds(int64 ms);
119 static TimeDelta FromSecondsD(double secs);
120 static TimeDelta FromMillisecondsD(double ms);
121 static TimeDelta FromMicroseconds(int64 us);
122#if defined(OS_WIN)
123 static TimeDelta FromQPCValue(LONGLONG qpc_value);
124#endif
125
126 // Converts an integer value representing TimeDelta to a class. This is used
127 // when deserializing a |TimeDelta| structure, using a value known to be
128 // compatible. It is not provided as a constructor because the integer type
129 // may be unclear from the perspective of a caller.
130 static TimeDelta FromInternalValue(int64 delta) {
131 return TimeDelta(delta);
132 }
133
134 // Returns the maximum time delta, which should be greater than any reasonable
135 // time delta we might compare it to. Adding or subtracting the maximum time
136 // delta to a time or another time delta has an undefined result.
137 static TimeDelta Max();
138
139 // Returns the internal numeric value of the TimeDelta object. Please don't
140 // use this and do arithmetic on it, as it is more error prone than using the
141 // provided operators.
142 // For serializing, use FromInternalValue to reconstitute.
143 int64 ToInternalValue() const {
144 return delta_;
145 }
146
147 // Returns the magnitude (absolute value) of this TimeDelta.
148 TimeDelta magnitude() const {
149 // Some toolchains provide an incomplete C++11 implementation and lack an
150 // int64 overload for std::abs(). The following is a simple branchless
151 // implementation:
152 const int64 mask = delta_ >> (sizeof(delta_) * 8 - 1);
153 return TimeDelta((delta_ + mask) ^ mask);
154 }
155
156 // Returns true if the time delta is zero.
157 bool is_zero() const {
158 return delta_ == 0;
159 }
160
161 // Returns true if the time delta is the maximum time delta.
162 bool is_max() const {
163 return delta_ == std::numeric_limits<int64>::max();
164 }
165
166#if defined(OS_POSIX)
167 struct timespec ToTimeSpec() const;
168#endif
169
170 // Returns the time delta in some unit. The F versions return a floating
171 // point value, the "regular" versions return a rounded-down value.
172 //
173 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
174 // to the next full millisecond.
175 int InDays() const;
176 int InHours() const;
177 int InMinutes() const;
178 double InSecondsF() const;
179 int64 InSeconds() const;
180 double InMillisecondsF() const;
181 int64 InMilliseconds() const;
182 int64 InMillisecondsRoundedUp() const;
183 int64 InMicroseconds() const;
184
185 TimeDelta& operator=(TimeDelta other) {
186 delta_ = other.delta_;
187 return *this;
188 }
189
190 // Computations with other deltas.
191 TimeDelta operator+(TimeDelta other) const {
192 return TimeDelta(time_internal::SaturatedAdd(*this, other.delta_));
193 }
194 TimeDelta operator-(TimeDelta other) const {
195 return TimeDelta(time_internal::SaturatedSub(*this, other.delta_));
196 }
197
198 TimeDelta& operator+=(TimeDelta other) {
199 return *this = (*this + other);
200 }
201 TimeDelta& operator-=(TimeDelta other) {
202 return *this = (*this - other);
203 }
204 TimeDelta operator-() const {
205 return TimeDelta(-delta_);
206 }
207
208 // Computations with numeric types.
209 template<typename T>
210 TimeDelta operator*(T a) const {
211 CheckedNumeric<int64> rv(delta_);
212 rv *= a;
213 return TimeDelta(time_internal::FromCheckedNumeric(rv));
214 }
215 template<typename T>
216 TimeDelta operator/(T a) const {
217 CheckedNumeric<int64> rv(delta_);
218 rv /= a;
219 return TimeDelta(time_internal::FromCheckedNumeric(rv));
220 }
221 template<typename T>
222 TimeDelta& operator*=(T a) {
223 return *this = (*this * a);
224 }
225 template<typename T>
226 TimeDelta& operator/=(T a) {
227 return *this = (*this / a);
228 }
229
230 int64 operator/(TimeDelta a) const {
231 return delta_ / a.delta_;
232 }
233 TimeDelta operator%(TimeDelta a) const {
234 return TimeDelta(delta_ % a.delta_);
235 }
236
237 // Comparison operators.
238 bool operator==(TimeDelta other) const {
239 return delta_ == other.delta_;
240 }
241 bool operator!=(TimeDelta other) const {
242 return delta_ != other.delta_;
243 }
244 bool operator<(TimeDelta other) const {
245 return delta_ < other.delta_;
246 }
247 bool operator<=(TimeDelta other) const {
248 return delta_ <= other.delta_;
249 }
250 bool operator>(TimeDelta other) const {
251 return delta_ > other.delta_;
252 }
253 bool operator>=(TimeDelta other) const {
254 return delta_ >= other.delta_;
255 }
256
257 private:
258 friend int64 time_internal::SaturatedAdd(TimeDelta delta, int64 value);
259 friend int64 time_internal::SaturatedSub(TimeDelta delta, int64 value);
260
261 // Constructs a delta given the duration in microseconds. This is private
262 // to avoid confusion by callers with an integer constructor. Use
263 // FromSeconds, FromMilliseconds, etc. instead.
264 explicit TimeDelta(int64 delta_us) : delta_(delta_us) {
265 }
266
267 // Delta in microseconds.
268 int64 delta_;
269};
270
271template<typename T>
272inline TimeDelta operator*(T a, TimeDelta td) {
273 return td * a;
274}
275
276// For logging use only.
277BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
278
279// Do not reference the time_internal::TimeBase template class directly. Please
280// use one of the time subclasses instead, and only reference the public
281// TimeBase members via those classes.
282namespace time_internal {
283
284// TimeBase--------------------------------------------------------------------
285
286// Provides value storage and comparison/math operations common to all time
287// classes. Each subclass provides for strong type-checking to ensure
288// semantically meaningful comparison/math of time values from the same clock
289// source or timeline.
290template<class TimeClass>
291class TimeBase {
292 public:
293 static const int64 kHoursPerDay = 24;
294 static const int64 kMillisecondsPerSecond = 1000;
295 static const int64 kMillisecondsPerDay = kMillisecondsPerSecond * 60 * 60 *
296 kHoursPerDay;
297 static const int64 kMicrosecondsPerMillisecond = 1000;
298 static const int64 kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
299 kMillisecondsPerSecond;
300 static const int64 kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
301 static const int64 kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
302 static const int64 kMicrosecondsPerDay = kMicrosecondsPerHour * kHoursPerDay;
303 static const int64 kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
304 static const int64 kNanosecondsPerMicrosecond = 1000;
305 static const int64 kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
306 kMicrosecondsPerSecond;
307
308 // Returns true if this object has not been initialized.
309 //
310 // Warning: Be careful when writing code that performs math on time values,
311 // since it's possible to produce a valid "zero" result that should not be
312 // interpreted as a "null" value.
313 bool is_null() const {
314 return us_ == 0;
315 }
316
317 // Returns true if this object represents the maximum time.
318 bool is_max() const {
319 return us_ == std::numeric_limits<int64>::max();
320 }
321
322 // For serializing only. Use FromInternalValue() to reconstitute. Please don't
323 // use this and do arithmetic on it, as it is more error prone than using the
324 // provided operators.
325 int64 ToInternalValue() const {
326 return us_;
327 }
328
329 TimeClass& operator=(TimeClass other) {
330 us_ = other.us_;
331 return *(static_cast<TimeClass*>(this));
332 }
333
334 // Compute the difference between two times.
335 TimeDelta operator-(TimeClass other) const {
336 return TimeDelta::FromMicroseconds(us_ - other.us_);
337 }
338
339 // Return a new time modified by some delta.
340 TimeClass operator+(TimeDelta delta) const {
341 return TimeClass(time_internal::SaturatedAdd(delta, us_));
342 }
343 TimeClass operator-(TimeDelta delta) const {
344 return TimeClass(-time_internal::SaturatedSub(delta, us_));
345 }
346
347 // Modify by some time delta.
348 TimeClass& operator+=(TimeDelta delta) {
349 return static_cast<TimeClass&>(*this = (*this + delta));
350 }
351 TimeClass& operator-=(TimeDelta delta) {
352 return static_cast<TimeClass&>(*this = (*this - delta));
353 }
354
355 // Comparison operators
356 bool operator==(TimeClass other) const {
357 return us_ == other.us_;
358 }
359 bool operator!=(TimeClass other) const {
360 return us_ != other.us_;
361 }
362 bool operator<(TimeClass other) const {
363 return us_ < other.us_;
364 }
365 bool operator<=(TimeClass other) const {
366 return us_ <= other.us_;
367 }
368 bool operator>(TimeClass other) const {
369 return us_ > other.us_;
370 }
371 bool operator>=(TimeClass other) const {
372 return us_ >= other.us_;
373 }
374
375 // Converts an integer value representing TimeClass to a class. This is used
376 // when deserializing a |TimeClass| structure, using a value known to be
377 // compatible. It is not provided as a constructor because the integer type
378 // may be unclear from the perspective of a caller.
379 static TimeClass FromInternalValue(int64 us) {
380 return TimeClass(us);
381 }
382
383 protected:
384 explicit TimeBase(int64 us) : us_(us) {
385 }
386
387 // Time value in a microsecond timebase.
388 int64 us_;
389};
390
391} // namespace time_internal
392
393template<class TimeClass>
394inline TimeClass operator+(TimeDelta delta, TimeClass t) {
395 return t + delta;
396}
397
398// Time -----------------------------------------------------------------------
399
400// Represents a wall clock time in UTC. Values are not guaranteed to be
401// monotonically non-decreasing and are subject to large amounts of skew.
402class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
403 public:
404 // The representation of Jan 1, 1970 UTC in microseconds since the
405 // platform-dependent epoch.
406 static const int64 kTimeTToMicrosecondsOffset;
407
408#if !defined(OS_WIN)
409 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
410 // the Posix delta of 1970. This is used for migrating between the old
411 // 1970-based epochs to the new 1601-based ones. It should be removed from
412 // this global header and put in the platform-specific ones when we remove the
413 // migration code.
414 static const int64 kWindowsEpochDeltaMicroseconds;
415#else
416 // To avoid overflow in QPC to Microseconds calculations, since we multiply
417 // by kMicrosecondsPerSecond, then the QPC value should not exceed
418 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
419 static const int64 kQPCOverflowThreshold = 0x8637BD05AF7;
420#endif
421
422 // Represents an exploded time that can be formatted nicely. This is kind of
423 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
424 // additions and changes to prevent errors.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700425 struct Exploded {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700426 int year; // Four digit year "2007"
427 int month; // 1-based month (values 1 = January, etc.)
428 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
429 int day_of_month; // 1-based day of month (1-31)
430 int hour; // Hour within the current day (0-23)
431 int minute; // Minute within the current hour (0-59)
432 int second; // Second within the current minute (0-59 plus leap
433 // seconds which may take it up to 60).
434 int millisecond; // Milliseconds within the current second (0-999)
435
436 // A cursory test for whether the data members are within their
437 // respective ranges. A 'true' return value does not guarantee the
438 // Exploded value can be successfully converted to a Time value.
439 bool HasValidValues() const;
440 };
441
442 // Contains the NULL time. Use Time::Now() to get the current time.
443 Time() : TimeBase(0) {
444 }
445
446 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
447 static Time UnixEpoch();
448
449 // Returns the current time. Watch out, the system might adjust its clock
450 // in which case time will actually go backwards. We don't guarantee that
451 // times are increasing, or that two calls to Now() won't be the same.
452 static Time Now();
453
454 // Returns the maximum time, which should be greater than any reasonable time
455 // with which we might compare it.
456 static Time Max();
457
458 // Returns the current time. Same as Now() except that this function always
459 // uses system time so that there are no discrepancies between the returned
460 // time and system time even on virtual environments including our test bot.
461 // For timing sensitive unittests, this function should be used.
462 static Time NowFromSystemTime();
463
464 // Converts to/from time_t in UTC and a Time class.
465 // TODO(brettw) this should be removed once everybody starts using the |Time|
466 // class.
467 static Time FromTimeT(time_t tt);
468 time_t ToTimeT() const;
469
470 // Converts time to/from a double which is the number of seconds since epoch
471 // (Jan 1, 1970). Webkit uses this format to represent time.
472 // Because WebKit initializes double time value to 0 to indicate "not
473 // initialized", we map it to empty Time object that also means "not
474 // initialized".
475 static Time FromDoubleT(double dt);
476 double ToDoubleT() const;
477
478#if defined(OS_POSIX)
479 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
480 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
481 // having a 1 second resolution, which agrees with
482 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
483 static Time FromTimeSpec(const timespec& ts);
484#endif
485
486 // Converts to/from the Javascript convention for times, a number of
487 // milliseconds since the epoch:
488 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
489 static Time FromJsTime(double ms_since_epoch);
490 double ToJsTime() const;
491
492 // Converts to Java convention for times, a number of
493 // milliseconds since the epoch.
494 int64 ToJavaTime() const;
495
496#if defined(OS_POSIX)
497 static Time FromTimeVal(struct timeval t);
498 struct timeval ToTimeVal() const;
499#endif
500
501#if defined(OS_MACOSX)
502 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
503 CFAbsoluteTime ToCFAbsoluteTime() const;
504#endif
505
506#if defined(OS_WIN)
507 static Time FromFileTime(FILETIME ft);
508 FILETIME ToFileTime() const;
509
510 // The minimum time of a low resolution timer. This is basically a windows
511 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
512 // treat it as static across all windows versions.
513 static const int kMinLowResolutionThresholdMs = 16;
514
515 // Enable or disable Windows high resolution timer.
516 static void EnableHighResolutionTimer(bool enable);
517
518 // Activates or deactivates the high resolution timer based on the |activate|
519 // flag. If the HighResolutionTimer is not Enabled (see
520 // EnableHighResolutionTimer), this function will return false. Otherwise
521 // returns true. Each successful activate call must be paired with a
522 // subsequent deactivate call.
523 // All callers to activate the high resolution timer must eventually call
524 // this function to deactivate the high resolution timer.
525 static bool ActivateHighResolutionTimer(bool activate);
526
527 // Returns true if the high resolution timer is both enabled and activated.
528 // This is provided for testing only, and is not tracked in a thread-safe
529 // way.
530 static bool IsHighResolutionTimerInUse();
531#endif
532
533 // Converts an exploded structure representing either the local time or UTC
534 // into a Time class.
535 static Time FromUTCExploded(const Exploded& exploded) {
536 return FromExploded(false, exploded);
537 }
538 static Time FromLocalExploded(const Exploded& exploded) {
539 return FromExploded(true, exploded);
540 }
541
Vitaly Bukacbed2062015-08-17 12:54:05 -0700542 // Fills the given exploded structure with either the local time or UTC from
543 // this time structure (containing UTC).
544 void UTCExplode(Exploded* exploded) const {
545 return Explode(false, exploded);
546 }
547 void LocalExplode(Exploded* exploded) const {
548 return Explode(true, exploded);
549 }
550
551 // Rounds this time down to the nearest day in local time. It will represent
552 // midnight on that day.
553 Time LocalMidnight() const;
554
555 private:
556 friend class time_internal::TimeBase<Time>;
557
558 explicit Time(int64 us) : TimeBase(us) {
559 }
560
561 // Explodes the given time to either local time |is_local = true| or UTC
562 // |is_local = false|.
563 void Explode(bool is_local, Exploded* exploded) const;
564
565 // Unexplodes a given time assuming the source is either local time
566 // |is_local = true| or UTC |is_local = false|.
567 static Time FromExploded(bool is_local, const Exploded& exploded);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700568};
569
570// Inline the TimeDelta factory methods, for fast TimeDelta construction.
571
572// static
573inline TimeDelta TimeDelta::FromDays(int days) {
574 // Preserve max to prevent overflow.
575 if (days == std::numeric_limits<int>::max())
576 return Max();
577 return TimeDelta(days * Time::kMicrosecondsPerDay);
578}
579
580// static
581inline TimeDelta TimeDelta::FromHours(int hours) {
582 // Preserve max to prevent overflow.
583 if (hours == std::numeric_limits<int>::max())
584 return Max();
585 return TimeDelta(hours * Time::kMicrosecondsPerHour);
586}
587
588// static
589inline TimeDelta TimeDelta::FromMinutes(int minutes) {
590 // Preserve max to prevent overflow.
591 if (minutes == std::numeric_limits<int>::max())
592 return Max();
593 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
594}
595
596// static
597inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
598 // Preserve max to prevent overflow.
599 if (secs == std::numeric_limits<int64>::max())
600 return Max();
601 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
602}
603
604// static
605inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
606 // Preserve max to prevent overflow.
607 if (ms == std::numeric_limits<int64>::max())
608 return Max();
609 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
610}
611
612// static
613inline TimeDelta TimeDelta::FromSecondsD(double secs) {
614 // Preserve max to prevent overflow.
615 if (secs == std::numeric_limits<double>::infinity())
616 return Max();
617 return TimeDelta(static_cast<int64>(secs * Time::kMicrosecondsPerSecond));
618}
619
620// static
621inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
622 // Preserve max to prevent overflow.
623 if (ms == std::numeric_limits<double>::infinity())
624 return Max();
625 return TimeDelta(static_cast<int64>(ms * Time::kMicrosecondsPerMillisecond));
626}
627
628// static
629inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
630 // Preserve max to prevent overflow.
631 if (us == std::numeric_limits<int64>::max())
632 return Max();
633 return TimeDelta(us);
634}
635
636// For logging use only.
637BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
638
639// TimeTicks ------------------------------------------------------------------
640
641// Represents monotonically non-decreasing clock time.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700642class TimeTicks : public time_internal::TimeBase<TimeTicks> {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700643 public:
644 TimeTicks() : TimeBase(0) {
645 }
646
647 // Platform-dependent tick count representing "right now." When
648 // IsHighResolution() returns false, the resolution of the clock could be
649 // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
650 // microsecond.
651 static TimeTicks Now();
652
653 // Returns true if the high resolution clock is working on this system and
654 // Now() will return high resolution values. Note that, on systems where the
655 // high resolution clock works but is deemed inefficient, the low resolution
656 // clock will be used instead.
657 static bool IsHighResolution();
658
659#if defined(OS_WIN)
660 // Translates an absolute QPC timestamp into a TimeTicks value. The returned
661 // value has the same origin as Now(). Do NOT attempt to use this if
662 // IsHighResolution() returns false.
663 static TimeTicks FromQPCValue(LONGLONG qpc_value);
664#endif
665
666 // Get the TimeTick value at the time of the UnixEpoch. This is useful when
667 // you need to relate the value of TimeTicks to a real time and date.
668 // Note: Upon first invocation, this function takes a snapshot of the realtime
669 // clock to establish a reference point. This function will return the same
670 // value for the duration of the application, but will be different in future
671 // application runs.
672 static TimeTicks UnixEpoch();
673
674 // Returns |this| snapped to the next tick, given a |tick_phase| and
675 // repeating |tick_interval| in both directions. |this| may be before,
676 // after, or equal to the |tick_phase|.
677 TimeTicks SnappedToNextTick(TimeTicks tick_phase,
678 TimeDelta tick_interval) const;
679
680#if defined(OS_WIN)
681 protected:
682 typedef DWORD (*TickFunctionType)(void);
683 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
684#endif
685
686 private:
687 friend class time_internal::TimeBase<TimeTicks>;
688
689 // Please use Now() to create a new object. This is for internal use
690 // and testing.
691 explicit TimeTicks(int64 us) : TimeBase(us) {
692 }
693};
694
695// For logging use only.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700696std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700697
698// ThreadTicks ----------------------------------------------------------------
699
700// Represents a clock, specific to a particular thread, than runs only while the
701// thread is running.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700702class ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700703 public:
704 ThreadTicks() : TimeBase(0) {
705 }
706
707 // Returns true if ThreadTicks::Now() is supported on this system.
708 static bool IsSupported() {
709#if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
710 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
711 return true;
712#else
713 return false;
714#endif
715 }
716
717 // Returns thread-specific CPU-time on systems that support this feature.
718 // Needs to be guarded with a call to IsSupported(). Use this timer
719 // to (approximately) measure how much time the calling thread spent doing
720 // actual work vs. being de-scheduled. May return bogus results if the thread
721 // migrates to another CPU between two calls.
722 static ThreadTicks Now();
723
724 private:
725 friend class time_internal::TimeBase<ThreadTicks>;
726
727 // Please use Now() to create a new object. This is for internal use
728 // and testing.
729 explicit ThreadTicks(int64 us) : TimeBase(us) {
730 }
731};
732
733// For logging use only.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700734std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700735
736// TraceTicks ----------------------------------------------------------------
737
738// Represents high-resolution system trace clock time.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700739class TraceTicks : public time_internal::TimeBase<TraceTicks> {
Vitaly Bukacbed2062015-08-17 12:54:05 -0700740 public:
741 // We define this even without OS_CHROMEOS for seccomp sandbox testing.
742#if defined(OS_LINUX)
743 // Force definition of the system trace clock; it is a chromeos-only api
744 // at the moment and surfacing it in the right place requires mucking
745 // with glibc et al.
746 static const clockid_t kClockSystemTrace = 11;
747#endif
748
749 TraceTicks() : TimeBase(0) {
750 }
751
752 // Returns the current system trace time or, if not available on this
753 // platform, a high-resolution time value; or a low-resolution time value if
754 // neither are avalable. On systems where a global trace clock is defined,
755 // timestamping TraceEvents's with this value guarantees synchronization
756 // between events collected inside chrome and events collected outside
757 // (e.g. kernel, X server).
758 //
759 // On some platforms, the clock source used for tracing can vary depending on
760 // hardware and/or kernel support. Do not make any assumptions without
761 // consulting the documentation for this functionality in the time_win.cc,
762 // time_posix.cc, etc. files.
763 //
764 // NOTE: This is only meant to be used by the event tracing infrastructure,
765 // and by outside code modules in special circumstances. Please be sure to
766 // consult a base/trace_event/OWNER before committing any new code that uses
767 // this.
768 static TraceTicks Now();
769
770 private:
771 friend class time_internal::TimeBase<TraceTicks>;
772
773 // Please use Now() to create a new object. This is for internal use
774 // and testing.
775 explicit TraceTicks(int64 us) : TimeBase(us) {
776 }
777};
778
779// For logging use only.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700780std::ostream& operator<<(std::ostream& os, TraceTicks time_ticks);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700781
782} // namespace base
783
784#endif // BASE_TIME_TIME_H_