Remove linux_chromium_gn_dbg from the chromium CQ.
[chromium-blink-merge.git] / base / time / time.h
blobe0a6ea37eaa9f2c2035a8b04ad80b9d3d7818223
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // 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.
13 // TimeDelta represents a duration of time, internally represented in
14 // microseconds.
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.
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).
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".
32 // So many choices! Which time class should you use? Examples:
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.
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.
46 // ThreadTicks: Benchmarking how long the current thread has been doing actual
47 // work.
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.
55 #ifndef BASE_TIME_TIME_H_
56 #define BASE_TIME_TIME_H_
58 #include <time.h>
60 #include <iosfwd>
62 #include "base/base_export.h"
63 #include "base/basictypes.h"
64 #include "base/numerics/safe_math.h"
65 #include "build/build_config.h"
67 #if defined(OS_MACOSX)
68 #include <CoreFoundation/CoreFoundation.h>
69 // Avoid Mac system header macro leak.
70 #undef TYPE_BOOL
71 #endif
73 #if defined(OS_POSIX)
74 #include <unistd.h>
75 #include <sys/time.h>
76 #endif
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
84 #include <limits>
86 namespace base {
88 class TimeDelta;
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.
93 namespace time_internal {
95 // Add or subtract |value| from a TimeDelta. The int64 argument and return value
96 // are in terms of a microsecond timebase.
97 BASE_EXPORT int64 SaturatedAdd(TimeDelta delta, int64 value);
98 BASE_EXPORT int64 SaturatedSub(TimeDelta delta, int64 value);
100 // Clamp |value| on overflow and underflow conditions. The int64 argument and
101 // return value are in terms of a microsecond timebase.
102 BASE_EXPORT int64 FromCheckedNumeric(const CheckedNumeric<int64> value);
104 } // namespace time_internal
106 // TimeDelta ------------------------------------------------------------------
108 class BASE_EXPORT TimeDelta {
109 public:
110 TimeDelta() : delta_(0) {
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
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);
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();
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_;
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);
156 // Returns true if the time delta is zero.
157 bool is_zero() const {
158 return delta_ == 0;
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();
166 #if defined(OS_POSIX)
167 struct timespec ToTimeSpec() const;
168 #endif
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.
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;
185 TimeDelta& operator=(TimeDelta other) {
186 delta_ = other.delta_;
187 return *this;
190 // Computations with other deltas.
191 TimeDelta operator+(TimeDelta other) const {
192 return TimeDelta(time_internal::SaturatedAdd(*this, other.delta_));
194 TimeDelta operator-(TimeDelta other) const {
195 return TimeDelta(time_internal::SaturatedSub(*this, other.delta_));
198 TimeDelta& operator+=(TimeDelta other) {
199 return *this = (*this + other);
201 TimeDelta& operator-=(TimeDelta other) {
202 return *this = (*this - other);
204 TimeDelta operator-() const {
205 return TimeDelta(-delta_);
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));
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));
221 template<typename T>
222 TimeDelta& operator*=(T a) {
223 return *this = (*this * a);
225 template<typename T>
226 TimeDelta& operator/=(T a) {
227 return *this = (*this / a);
230 int64 operator/(TimeDelta a) const {
231 return delta_ / a.delta_;
233 TimeDelta operator%(TimeDelta a) const {
234 return TimeDelta(delta_ % a.delta_);
237 // Comparison operators.
238 bool operator==(TimeDelta other) const {
239 return delta_ == other.delta_;
241 bool operator!=(TimeDelta other) const {
242 return delta_ != other.delta_;
244 bool operator<(TimeDelta other) const {
245 return delta_ < other.delta_;
247 bool operator<=(TimeDelta other) const {
248 return delta_ <= other.delta_;
250 bool operator>(TimeDelta other) const {
251 return delta_ > other.delta_;
253 bool operator>=(TimeDelta other) const {
254 return delta_ >= other.delta_;
257 private:
258 friend int64 time_internal::SaturatedAdd(TimeDelta delta, int64 value);
259 friend int64 time_internal::SaturatedSub(TimeDelta delta, int64 value);
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) {
267 // Private method to build a delta from a double.
268 static TimeDelta FromDouble(double value);
270 // Delta in microseconds.
271 int64 delta_;
274 template<typename T>
275 inline TimeDelta operator*(T a, TimeDelta td) {
276 return td * a;
279 // For logging use only.
280 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
282 // Do not reference the time_internal::TimeBase template class directly. Please
283 // use one of the time subclasses instead, and only reference the public
284 // TimeBase members via those classes.
285 namespace time_internal {
287 // TimeBase--------------------------------------------------------------------
289 // Provides value storage and comparison/math operations common to all time
290 // classes. Each subclass provides for strong type-checking to ensure
291 // semantically meaningful comparison/math of time values from the same clock
292 // source or timeline.
293 template<class TimeClass>
294 class TimeBase {
295 public:
296 static const int64 kHoursPerDay = 24;
297 static const int64 kMillisecondsPerSecond = 1000;
298 static const int64 kMillisecondsPerDay = kMillisecondsPerSecond * 60 * 60 *
299 kHoursPerDay;
300 static const int64 kMicrosecondsPerMillisecond = 1000;
301 static const int64 kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
302 kMillisecondsPerSecond;
303 static const int64 kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
304 static const int64 kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
305 static const int64 kMicrosecondsPerDay = kMicrosecondsPerHour * kHoursPerDay;
306 static const int64 kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
307 static const int64 kNanosecondsPerMicrosecond = 1000;
308 static const int64 kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
309 kMicrosecondsPerSecond;
311 // Returns true if this object has not been initialized.
313 // Warning: Be careful when writing code that performs math on time values,
314 // since it's possible to produce a valid "zero" result that should not be
315 // interpreted as a "null" value.
316 bool is_null() const {
317 return us_ == 0;
320 // Returns true if this object represents the maximum time.
321 bool is_max() const {
322 return us_ == std::numeric_limits<int64>::max();
325 // For serializing only. Use FromInternalValue() to reconstitute. Please don't
326 // use this and do arithmetic on it, as it is more error prone than using the
327 // provided operators.
328 int64 ToInternalValue() const {
329 return us_;
332 TimeClass& operator=(TimeClass other) {
333 us_ = other.us_;
334 return *(static_cast<TimeClass*>(this));
337 // Compute the difference between two times.
338 TimeDelta operator-(TimeClass other) const {
339 return TimeDelta::FromMicroseconds(us_ - other.us_);
342 // Return a new time modified by some delta.
343 TimeClass operator+(TimeDelta delta) const {
344 return TimeClass(time_internal::SaturatedAdd(delta, us_));
346 TimeClass operator-(TimeDelta delta) const {
347 return TimeClass(-time_internal::SaturatedSub(delta, us_));
350 // Modify by some time delta.
351 TimeClass& operator+=(TimeDelta delta) {
352 return static_cast<TimeClass&>(*this = (*this + delta));
354 TimeClass& operator-=(TimeDelta delta) {
355 return static_cast<TimeClass&>(*this = (*this - delta));
358 // Comparison operators
359 bool operator==(TimeClass other) const {
360 return us_ == other.us_;
362 bool operator!=(TimeClass other) const {
363 return us_ != other.us_;
365 bool operator<(TimeClass other) const {
366 return us_ < other.us_;
368 bool operator<=(TimeClass other) const {
369 return us_ <= other.us_;
371 bool operator>(TimeClass other) const {
372 return us_ > other.us_;
374 bool operator>=(TimeClass other) const {
375 return us_ >= other.us_;
378 // Converts an integer value representing TimeClass to a class. This is used
379 // when deserializing a |TimeClass| structure, using a value known to be
380 // compatible. It is not provided as a constructor because the integer type
381 // may be unclear from the perspective of a caller.
382 static TimeClass FromInternalValue(int64 us) {
383 return TimeClass(us);
386 protected:
387 explicit TimeBase(int64 us) : us_(us) {
390 // Time value in a microsecond timebase.
391 int64 us_;
394 } // namespace time_internal
396 template<class TimeClass>
397 inline TimeClass operator+(TimeDelta delta, TimeClass t) {
398 return t + delta;
401 // Time -----------------------------------------------------------------------
403 // Represents a wall clock time in UTC. Values are not guaranteed to be
404 // monotonically non-decreasing and are subject to large amounts of skew.
405 class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
406 public:
407 // The representation of Jan 1, 1970 UTC in microseconds since the
408 // platform-dependent epoch.
409 static const int64 kTimeTToMicrosecondsOffset;
411 #if !defined(OS_WIN)
412 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
413 // the Posix delta of 1970. This is used for migrating between the old
414 // 1970-based epochs to the new 1601-based ones. It should be removed from
415 // this global header and put in the platform-specific ones when we remove the
416 // migration code.
417 static const int64 kWindowsEpochDeltaMicroseconds;
418 #else
419 // To avoid overflow in QPC to Microseconds calculations, since we multiply
420 // by kMicrosecondsPerSecond, then the QPC value should not exceed
421 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
422 static const int64 kQPCOverflowThreshold = 0x8637BD05AF7;
423 #endif
425 // Represents an exploded time that can be formatted nicely. This is kind of
426 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
427 // additions and changes to prevent errors.
428 struct BASE_EXPORT Exploded {
429 int year; // Four digit year "2007"
430 int month; // 1-based month (values 1 = January, etc.)
431 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
432 int day_of_month; // 1-based day of month (1-31)
433 int hour; // Hour within the current day (0-23)
434 int minute; // Minute within the current hour (0-59)
435 int second; // Second within the current minute (0-59 plus leap
436 // seconds which may take it up to 60).
437 int millisecond; // Milliseconds within the current second (0-999)
439 // A cursory test for whether the data members are within their
440 // respective ranges. A 'true' return value does not guarantee the
441 // Exploded value can be successfully converted to a Time value.
442 bool HasValidValues() const;
445 // Contains the NULL time. Use Time::Now() to get the current time.
446 Time() : TimeBase(0) {
449 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
450 static Time UnixEpoch();
452 // Returns the current time. Watch out, the system might adjust its clock
453 // in which case time will actually go backwards. We don't guarantee that
454 // times are increasing, or that two calls to Now() won't be the same.
455 static Time Now();
457 // Returns the maximum time, which should be greater than any reasonable time
458 // with which we might compare it.
459 static Time Max();
461 // Returns the current time. Same as Now() except that this function always
462 // uses system time so that there are no discrepancies between the returned
463 // time and system time even on virtual environments including our test bot.
464 // For timing sensitive unittests, this function should be used.
465 static Time NowFromSystemTime();
467 // Converts to/from time_t in UTC and a Time class.
468 // TODO(brettw) this should be removed once everybody starts using the |Time|
469 // class.
470 static Time FromTimeT(time_t tt);
471 time_t ToTimeT() const;
473 // Converts time to/from a double which is the number of seconds since epoch
474 // (Jan 1, 1970). Webkit uses this format to represent time.
475 // Because WebKit initializes double time value to 0 to indicate "not
476 // initialized", we map it to empty Time object that also means "not
477 // initialized".
478 static Time FromDoubleT(double dt);
479 double ToDoubleT() const;
481 #if defined(OS_POSIX)
482 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
483 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
484 // having a 1 second resolution, which agrees with
485 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
486 static Time FromTimeSpec(const timespec& ts);
487 #endif
489 // Converts to/from the Javascript convention for times, a number of
490 // milliseconds since the epoch:
491 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
492 static Time FromJsTime(double ms_since_epoch);
493 double ToJsTime() const;
495 // Converts to Java convention for times, a number of
496 // milliseconds since the epoch.
497 int64 ToJavaTime() const;
499 #if defined(OS_POSIX)
500 static Time FromTimeVal(struct timeval t);
501 struct timeval ToTimeVal() const;
502 #endif
504 #if defined(OS_MACOSX)
505 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
506 CFAbsoluteTime ToCFAbsoluteTime() const;
507 #endif
509 #if defined(OS_WIN)
510 static Time FromFileTime(FILETIME ft);
511 FILETIME ToFileTime() const;
513 // The minimum time of a low resolution timer. This is basically a windows
514 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
515 // treat it as static across all windows versions.
516 static const int kMinLowResolutionThresholdMs = 16;
518 // Enable or disable Windows high resolution timer.
519 static void EnableHighResolutionTimer(bool enable);
521 // Activates or deactivates the high resolution timer based on the |activate|
522 // flag. If the HighResolutionTimer is not Enabled (see
523 // EnableHighResolutionTimer), this function will return false. Otherwise
524 // returns true. Each successful activate call must be paired with a
525 // subsequent deactivate call.
526 // All callers to activate the high resolution timer must eventually call
527 // this function to deactivate the high resolution timer.
528 static bool ActivateHighResolutionTimer(bool activate);
530 // Returns true if the high resolution timer is both enabled and activated.
531 // This is provided for testing only, and is not tracked in a thread-safe
532 // way.
533 static bool IsHighResolutionTimerInUse();
534 #endif
536 // Converts an exploded structure representing either the local time or UTC
537 // into a Time class.
538 static Time FromUTCExploded(const Exploded& exploded) {
539 return FromExploded(false, exploded);
541 static Time FromLocalExploded(const Exploded& exploded) {
542 return FromExploded(true, exploded);
545 // Converts a string representation of time to a Time object.
546 // An example of a time string which is converted is as below:-
547 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
548 // in the input string, FromString assumes local time and FromUTCString
549 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
550 // specified in RFC822) is treated as if the timezone is not specified.
551 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
552 // a new time converter class.
553 static bool FromString(const char* time_string, Time* parsed_time) {
554 return FromStringInternal(time_string, true, parsed_time);
556 static bool FromUTCString(const char* time_string, Time* parsed_time) {
557 return FromStringInternal(time_string, false, parsed_time);
560 // Fills the given exploded structure with either the local time or UTC from
561 // this time structure (containing UTC).
562 void UTCExplode(Exploded* exploded) const {
563 return Explode(false, exploded);
565 void LocalExplode(Exploded* exploded) const {
566 return Explode(true, exploded);
569 // Rounds this time down to the nearest day in local time. It will represent
570 // midnight on that day.
571 Time LocalMidnight() const;
573 private:
574 friend class time_internal::TimeBase<Time>;
576 explicit Time(int64 us) : TimeBase(us) {
579 // Explodes the given time to either local time |is_local = true| or UTC
580 // |is_local = false|.
581 void Explode(bool is_local, Exploded* exploded) const;
583 // Unexplodes a given time assuming the source is either local time
584 // |is_local = true| or UTC |is_local = false|.
585 static Time FromExploded(bool is_local, const Exploded& exploded);
587 // Converts a string representation of time to a Time object.
588 // An example of a time string which is converted is as below:-
589 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
590 // in the input string, local time |is_local = true| or
591 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
592 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
593 // timezone is not specified.
594 static bool FromStringInternal(const char* time_string,
595 bool is_local,
596 Time* parsed_time);
599 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
601 // static
602 inline TimeDelta TimeDelta::FromDays(int days) {
603 if (days == std::numeric_limits<int>::max())
604 return Max();
605 return TimeDelta(days * Time::kMicrosecondsPerDay);
608 // static
609 inline TimeDelta TimeDelta::FromHours(int hours) {
610 if (hours == std::numeric_limits<int>::max())
611 return Max();
612 return TimeDelta(hours * Time::kMicrosecondsPerHour);
615 // static
616 inline TimeDelta TimeDelta::FromMinutes(int minutes) {
617 if (minutes == std::numeric_limits<int>::max())
618 return Max();
619 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
622 // static
623 inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
624 return TimeDelta(secs) * Time::kMicrosecondsPerSecond;
627 // static
628 inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
629 return TimeDelta(ms) * Time::kMicrosecondsPerMillisecond;
632 // static
633 inline TimeDelta TimeDelta::FromSecondsD(double secs) {
634 return FromDouble(secs * Time::kMicrosecondsPerSecond);
637 // static
638 inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
639 return FromDouble(ms * Time::kMicrosecondsPerMillisecond);
642 // static
643 inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
644 return TimeDelta(us);
647 // static
648 inline TimeDelta TimeDelta::FromDouble(double value) {
649 double max_magnitude = std::numeric_limits<int64>::max();
650 TimeDelta delta = TimeDelta(static_cast<int64>(value));
651 if (value > max_magnitude)
652 delta = Max();
653 else if (value < -max_magnitude)
654 delta = -Max();
655 return delta;
658 // For logging use only.
659 BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
661 // TimeTicks ------------------------------------------------------------------
663 // Represents monotonically non-decreasing clock time.
664 class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> {
665 public:
666 TimeTicks() : TimeBase(0) {
669 // Platform-dependent tick count representing "right now." When
670 // IsHighResolution() returns false, the resolution of the clock could be
671 // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
672 // microsecond.
673 static TimeTicks Now();
675 // Returns true if the high resolution clock is working on this system and
676 // Now() will return high resolution values. Note that, on systems where the
677 // high resolution clock works but is deemed inefficient, the low resolution
678 // clock will be used instead.
679 static bool IsHighResolution();
681 #if defined(OS_WIN)
682 // Translates an absolute QPC timestamp into a TimeTicks value. The returned
683 // value has the same origin as Now(). Do NOT attempt to use this if
684 // IsHighResolution() returns false.
685 static TimeTicks FromQPCValue(LONGLONG qpc_value);
686 #endif
688 // Get the TimeTick value at the time of the UnixEpoch. This is useful when
689 // you need to relate the value of TimeTicks to a real time and date.
690 // Note: Upon first invocation, this function takes a snapshot of the realtime
691 // clock to establish a reference point. This function will return the same
692 // value for the duration of the application, but will be different in future
693 // application runs.
694 static TimeTicks UnixEpoch();
696 // Returns |this| snapped to the next tick, given a |tick_phase| and
697 // repeating |tick_interval| in both directions. |this| may be before,
698 // after, or equal to the |tick_phase|.
699 TimeTicks SnappedToNextTick(TimeTicks tick_phase,
700 TimeDelta tick_interval) const;
702 #if defined(OS_WIN)
703 protected:
704 typedef DWORD (*TickFunctionType)(void);
705 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
706 #endif
708 private:
709 friend class time_internal::TimeBase<TimeTicks>;
711 // Please use Now() to create a new object. This is for internal use
712 // and testing.
713 explicit TimeTicks(int64 us) : TimeBase(us) {
717 // For logging use only.
718 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
720 // ThreadTicks ----------------------------------------------------------------
722 // Represents a clock, specific to a particular thread, than runs only while the
723 // thread is running.
724 class BASE_EXPORT ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
725 public:
726 ThreadTicks() : TimeBase(0) {
729 // Returns true if ThreadTicks::Now() is supported on this system.
730 static bool IsSupported() {
731 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
732 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
733 return true;
734 #else
735 return false;
736 #endif
739 // Returns thread-specific CPU-time on systems that support this feature.
740 // Needs to be guarded with a call to IsSupported(). Use this timer
741 // to (approximately) measure how much time the calling thread spent doing
742 // actual work vs. being de-scheduled. May return bogus results if the thread
743 // migrates to another CPU between two calls.
744 static ThreadTicks Now();
746 private:
747 friend class time_internal::TimeBase<ThreadTicks>;
749 // Please use Now() to create a new object. This is for internal use
750 // and testing.
751 explicit ThreadTicks(int64 us) : TimeBase(us) {
755 // For logging use only.
756 BASE_EXPORT std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
758 // TraceTicks ----------------------------------------------------------------
760 // Represents high-resolution system trace clock time.
761 class BASE_EXPORT TraceTicks : public time_internal::TimeBase<TraceTicks> {
762 public:
763 // We define this even without OS_CHROMEOS for seccomp sandbox testing.
764 #if defined(OS_LINUX)
765 // Force definition of the system trace clock; it is a chromeos-only api
766 // at the moment and surfacing it in the right place requires mucking
767 // with glibc et al.
768 static const clockid_t kClockSystemTrace = 11;
769 #endif
771 TraceTicks() : TimeBase(0) {
774 // Returns the current system trace time or, if not available on this
775 // platform, a high-resolution time value; or a low-resolution time value if
776 // neither are avalable. On systems where a global trace clock is defined,
777 // timestamping TraceEvents's with this value guarantees synchronization
778 // between events collected inside chrome and events collected outside
779 // (e.g. kernel, X server).
781 // On some platforms, the clock source used for tracing can vary depending on
782 // hardware and/or kernel support. Do not make any assumptions without
783 // consulting the documentation for this functionality in the time_win.cc,
784 // time_posix.cc, etc. files.
786 // NOTE: This is only meant to be used by the event tracing infrastructure,
787 // and by outside code modules in special circumstances. Please be sure to
788 // consult a base/trace_event/OWNER before committing any new code that uses
789 // this.
790 static TraceTicks Now();
792 private:
793 friend class time_internal::TimeBase<TraceTicks>;
795 // Please use Now() to create a new object. This is for internal use
796 // and testing.
797 explicit TraceTicks(int64 us) : TimeBase(us) {
801 // For logging use only.
802 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TraceTicks time_ticks);
804 } // namespace base
806 #endif // BASE_TIME_TIME_H_