Use multiline attribute to check for IA2_STATE_MULTILINE.
[chromium-blink-merge.git] / base / time / time.h
blob5c8b89c18cf174529c3220d1be399366ee15352e
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) (See http://crbug.com/14734). System-dependent
8 // clock interface routines are defined in time_PLATFORM.cc.
9 //
10 // TimeDelta represents a duration of time, internally represented in
11 // microseconds.
13 // TimeTicks represents an abstract time that is most of the time incrementing
14 // for use in measuring time durations. It is internally represented in
15 // microseconds. It can not be converted to a human-readable time, but is
16 // guaranteed not to decrease (if the user changes the computer clock,
17 // Time::Now() may actually decrease or jump). But note that TimeTicks may
18 // "stand still", for example if the computer suspended.
20 // These classes are represented as only a 64-bit value, so they can be
21 // efficiently passed by value.
23 // Definitions of operator<< are provided to make these types work with
24 // DCHECK_EQ() and other log macros. For human-readable formatting, see
25 // "base/i18n/time_formatting.h".
27 #ifndef BASE_TIME_TIME_H_
28 #define BASE_TIME_TIME_H_
30 #include <time.h>
32 #include <iosfwd>
34 #include "base/base_export.h"
35 #include "base/basictypes.h"
36 #include "base/numerics/safe_math.h"
37 #include "build/build_config.h"
39 #if defined(OS_MACOSX)
40 #include <CoreFoundation/CoreFoundation.h>
41 // Avoid Mac system header macro leak.
42 #undef TYPE_BOOL
43 #endif
45 #if defined(OS_POSIX)
46 #include <unistd.h>
47 #include <sys/time.h>
48 #endif
50 #if defined(OS_WIN)
51 // For FILETIME in FromFileTime, until it moves to a new converter class.
52 // See TODO(iyengar) below.
53 #include <windows.h>
54 #endif
56 #include <limits>
58 namespace base {
60 class Time;
61 class TimeTicks;
63 // TimeDelta ------------------------------------------------------------------
65 class BASE_EXPORT TimeDelta {
66 public:
67 TimeDelta() : delta_(0) {
70 // Converts units of time to TimeDeltas.
71 static TimeDelta FromDays(int days);
72 static TimeDelta FromHours(int hours);
73 static TimeDelta FromMinutes(int minutes);
74 static TimeDelta FromSeconds(int64 secs);
75 static TimeDelta FromMilliseconds(int64 ms);
76 static TimeDelta FromSecondsD(double secs);
77 static TimeDelta FromMillisecondsD(double ms);
78 static TimeDelta FromMicroseconds(int64 us);
79 #if defined(OS_WIN)
80 static TimeDelta FromQPCValue(LONGLONG qpc_value);
81 #endif
83 // Converts an integer value representing TimeDelta to a class. This is used
84 // when deserializing a |TimeDelta| structure, using a value known to be
85 // compatible. It is not provided as a constructor because the integer type
86 // may be unclear from the perspective of a caller.
87 static TimeDelta FromInternalValue(int64 delta) {
88 return TimeDelta(delta);
91 // Returns the maximum time delta, which should be greater than any reasonable
92 // time delta we might compare it to. Adding or subtracting the maximum time
93 // delta to a time or another time delta has an undefined result.
94 static TimeDelta Max();
96 // Returns the internal numeric value of the TimeDelta object. Please don't
97 // use this and do arithmetic on it, as it is more error prone than using the
98 // provided operators.
99 // For serializing, use FromInternalValue to reconstitute.
100 int64 ToInternalValue() const {
101 return delta_;
104 // Returns the magnitude (absolute value) of this TimeDelta.
105 TimeDelta magnitude() const {
106 // Some toolchains provide an incomplete C++11 implementation and lack an
107 // int64 overload for std::abs(). The following is a simple branchless
108 // implementation:
109 const int64 mask = delta_ >> (sizeof(delta_) * 8 - 1);
110 return TimeDelta((delta_ + mask) ^ mask);
113 // Returns true if the time delta is the maximum time delta.
114 bool is_max() const {
115 return delta_ == std::numeric_limits<int64>::max();
118 #if defined(OS_POSIX)
119 struct timespec ToTimeSpec() const;
120 #endif
122 // Returns the time delta in some unit. The F versions return a floating
123 // point value, the "regular" versions return a rounded-down value.
125 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
126 // to the next full millisecond.
127 int InDays() const;
128 int InHours() const;
129 int InMinutes() const;
130 double InSecondsF() const;
131 int64 InSeconds() const;
132 double InMillisecondsF() const;
133 int64 InMilliseconds() const;
134 int64 InMillisecondsRoundedUp() const;
135 int64 InMicroseconds() const;
137 TimeDelta& operator=(TimeDelta other) {
138 delta_ = other.delta_;
139 return *this;
142 // Computations with other deltas.
143 TimeDelta operator+(TimeDelta other) const {
144 return TimeDelta(SaturatedAdd(other.delta_));
146 TimeDelta operator-(TimeDelta other) const {
147 return TimeDelta(SaturatedSub(other.delta_));
150 TimeDelta& operator+=(TimeDelta other) {
151 delta_ = SaturatedAdd(other.delta_);
152 return *this;
154 TimeDelta& operator-=(TimeDelta other) {
155 delta_ = SaturatedSub(other.delta_);
156 return *this;
158 TimeDelta operator-() const {
159 return TimeDelta(-delta_);
162 // Computations with numeric types.
163 template<typename T>
164 TimeDelta operator*(T a) const {
165 CheckedNumeric<int64> rv(delta_);
166 rv *= a;
167 return TimeDelta(FromCheckedNumeric(rv));
169 template<typename T>
170 TimeDelta operator/(T a) const {
171 CheckedNumeric<int64> rv(delta_);
172 rv /= a;
173 return TimeDelta(FromCheckedNumeric(rv));
175 template<typename T>
176 TimeDelta& operator*=(T a) {
177 CheckedNumeric<int64> rv(delta_);
178 rv *= a;
179 delta_ = FromCheckedNumeric(rv);
180 return *this;
182 template<typename T>
183 TimeDelta& operator/=(T a) {
184 CheckedNumeric<int64> rv(delta_);
185 rv /= a;
186 delta_ = FromCheckedNumeric(rv);
187 return *this;
190 int64 operator/(TimeDelta a) const {
191 return delta_ / a.delta_;
194 // Defined below because it depends on the definition of the other classes.
195 Time operator+(Time t) const;
196 TimeTicks operator+(TimeTicks t) const;
198 // Comparison operators.
199 bool operator==(TimeDelta other) const {
200 return delta_ == other.delta_;
202 bool operator!=(TimeDelta other) const {
203 return delta_ != other.delta_;
205 bool operator<(TimeDelta other) const {
206 return delta_ < other.delta_;
208 bool operator<=(TimeDelta other) const {
209 return delta_ <= other.delta_;
211 bool operator>(TimeDelta other) const {
212 return delta_ > other.delta_;
214 bool operator>=(TimeDelta other) const {
215 return delta_ >= other.delta_;
218 private:
219 friend class Time;
220 friend class TimeTicks;
222 // Constructs a delta given the duration in microseconds. This is private
223 // to avoid confusion by callers with an integer constructor. Use
224 // FromSeconds, FromMilliseconds, etc. instead.
225 explicit TimeDelta(int64 delta_us) : delta_(delta_us) {
228 // Add or subtract |value| from this delta.
229 int64 SaturatedAdd(int64 value) const;
230 int64 SaturatedSub(int64 value) const;
232 // Clamp |value| on overflow and underflow conditions.
233 static int64 FromCheckedNumeric(const CheckedNumeric<int64> value);
235 // Delta in microseconds.
236 int64 delta_;
239 template<typename T>
240 inline TimeDelta operator*(T a, TimeDelta td) {
241 return td * a;
244 // For logging use only.
245 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
247 // Time -----------------------------------------------------------------------
249 // Represents a wall clock time in UTC.
250 class BASE_EXPORT Time {
251 public:
252 static const int64 kHoursPerDay = 24;
253 static const int64 kMillisecondsPerSecond = 1000;
254 static const int64 kMillisecondsPerDay = kMillisecondsPerSecond * 60 * 60 *
255 kHoursPerDay;
256 static const int64 kMicrosecondsPerMillisecond = 1000;
257 static const int64 kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
258 kMillisecondsPerSecond;
259 static const int64 kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
260 static const int64 kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
261 static const int64 kMicrosecondsPerDay = kMicrosecondsPerHour * kHoursPerDay;
262 static const int64 kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
263 static const int64 kNanosecondsPerMicrosecond = 1000;
264 static const int64 kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
265 kMicrosecondsPerSecond;
267 // The representation of Jan 1, 1970 UTC in microseconds since the
268 // platform-dependent epoch.
269 static const int64 kTimeTToMicrosecondsOffset;
271 #if !defined(OS_WIN)
272 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
273 // the Posix delta of 1970. This is used for migrating between the old
274 // 1970-based epochs to the new 1601-based ones. It should be removed from
275 // this global header and put in the platform-specific ones when we remove the
276 // migration code.
277 static const int64 kWindowsEpochDeltaMicroseconds;
278 #else
279 // To avoid overflow in QPC to Microseconds calculations, since we multiply
280 // by kMicrosecondsPerSecond, then the QPC value should not exceed
281 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
282 static const int64 kQPCOverflowThreshold = 0x8637BD05AF7;
283 #endif
285 // Represents an exploded time that can be formatted nicely. This is kind of
286 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
287 // additions and changes to prevent errors.
288 struct BASE_EXPORT Exploded {
289 int year; // Four digit year "2007"
290 int month; // 1-based month (values 1 = January, etc.)
291 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
292 int day_of_month; // 1-based day of month (1-31)
293 int hour; // Hour within the current day (0-23)
294 int minute; // Minute within the current hour (0-59)
295 int second; // Second within the current minute (0-59 plus leap
296 // seconds which may take it up to 60).
297 int millisecond; // Milliseconds within the current second (0-999)
299 // A cursory test for whether the data members are within their
300 // respective ranges. A 'true' return value does not guarantee the
301 // Exploded value can be successfully converted to a Time value.
302 bool HasValidValues() const;
305 // Contains the NULL time. Use Time::Now() to get the current time.
306 Time() : us_(0) {
309 // Returns true if the time object has not been initialized.
310 bool is_null() const {
311 return us_ == 0;
314 // Returns true if the time object is the maximum time.
315 bool is_max() const {
316 return us_ == std::numeric_limits<int64>::max();
319 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
320 static Time UnixEpoch();
322 // Returns the current time. Watch out, the system might adjust its clock
323 // in which case time will actually go backwards. We don't guarantee that
324 // times are increasing, or that two calls to Now() won't be the same.
325 static Time Now();
327 // Returns the maximum time, which should be greater than any reasonable time
328 // with which we might compare it.
329 static Time Max();
331 // Returns the current time. Same as Now() except that this function always
332 // uses system time so that there are no discrepancies between the returned
333 // time and system time even on virtual environments including our test bot.
334 // For timing sensitive unittests, this function should be used.
335 static Time NowFromSystemTime();
337 // Converts to/from time_t in UTC and a Time class.
338 // TODO(brettw) this should be removed once everybody starts using the |Time|
339 // class.
340 static Time FromTimeT(time_t tt);
341 time_t ToTimeT() const;
343 // Converts time to/from a double which is the number of seconds since epoch
344 // (Jan 1, 1970). Webkit uses this format to represent time.
345 // Because WebKit initializes double time value to 0 to indicate "not
346 // initialized", we map it to empty Time object that also means "not
347 // initialized".
348 static Time FromDoubleT(double dt);
349 double ToDoubleT() const;
351 #if defined(OS_POSIX)
352 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
353 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
354 // having a 1 second resolution, which agrees with
355 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
356 static Time FromTimeSpec(const timespec& ts);
357 #endif
359 // Converts to/from the Javascript convention for times, a number of
360 // milliseconds since the epoch:
361 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
362 static Time FromJsTime(double ms_since_epoch);
363 double ToJsTime() const;
365 // Converts to Java convention for times, a number of
366 // milliseconds since the epoch.
367 int64 ToJavaTime() const;
369 #if defined(OS_POSIX)
370 static Time FromTimeVal(struct timeval t);
371 struct timeval ToTimeVal() const;
372 #endif
374 #if defined(OS_MACOSX)
375 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
376 CFAbsoluteTime ToCFAbsoluteTime() const;
377 #endif
379 #if defined(OS_WIN)
380 static Time FromFileTime(FILETIME ft);
381 FILETIME ToFileTime() const;
383 // The minimum time of a low resolution timer. This is basically a windows
384 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
385 // treat it as static across all windows versions.
386 static const int kMinLowResolutionThresholdMs = 16;
388 // Enable or disable Windows high resolution timer.
389 static void EnableHighResolutionTimer(bool enable);
391 // Activates or deactivates the high resolution timer based on the |activate|
392 // flag. If the HighResolutionTimer is not Enabled (see
393 // EnableHighResolutionTimer), this function will return false. Otherwise
394 // returns true. Each successful activate call must be paired with a
395 // subsequent deactivate call.
396 // All callers to activate the high resolution timer must eventually call
397 // this function to deactivate the high resolution timer.
398 static bool ActivateHighResolutionTimer(bool activate);
400 // Returns true if the high resolution timer is both enabled and activated.
401 // This is provided for testing only, and is not tracked in a thread-safe
402 // way.
403 static bool IsHighResolutionTimerInUse();
404 #endif
406 // Converts an exploded structure representing either the local time or UTC
407 // into a Time class.
408 static Time FromUTCExploded(const Exploded& exploded) {
409 return FromExploded(false, exploded);
411 static Time FromLocalExploded(const Exploded& exploded) {
412 return FromExploded(true, exploded);
415 // Converts an integer value representing Time to a class. This is used
416 // when deserializing a |Time| structure, using a value known to be
417 // compatible. It is not provided as a constructor because the integer type
418 // may be unclear from the perspective of a caller.
419 static Time FromInternalValue(int64 us) {
420 return Time(us);
423 // Converts a string representation of time to a Time object.
424 // An example of a time string which is converted is as below:-
425 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
426 // in the input string, FromString assumes local time and FromUTCString
427 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
428 // specified in RFC822) is treated as if the timezone is not specified.
429 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
430 // a new time converter class.
431 static bool FromString(const char* time_string, Time* parsed_time) {
432 return FromStringInternal(time_string, true, parsed_time);
434 static bool FromUTCString(const char* time_string, Time* parsed_time) {
435 return FromStringInternal(time_string, false, parsed_time);
438 // For serializing, use FromInternalValue to reconstitute. Please don't use
439 // this and do arithmetic on it, as it is more error prone than using the
440 // provided operators.
441 int64 ToInternalValue() const {
442 return us_;
445 // Fills the given exploded structure with either the local time or UTC from
446 // this time structure (containing UTC).
447 void UTCExplode(Exploded* exploded) const {
448 return Explode(false, exploded);
450 void LocalExplode(Exploded* exploded) const {
451 return Explode(true, exploded);
454 // Rounds this time down to the nearest day in local time. It will represent
455 // midnight on that day.
456 Time LocalMidnight() const;
458 Time& operator=(Time other) {
459 us_ = other.us_;
460 return *this;
463 // Compute the difference between two times.
464 TimeDelta operator-(Time other) const {
465 return TimeDelta(us_ - other.us_);
468 // Modify by some time delta.
469 Time& operator+=(TimeDelta delta) {
470 us_ = delta.SaturatedAdd(us_);
471 return *this;
473 Time& operator-=(TimeDelta delta) {
474 us_ = -delta.SaturatedSub(us_);
475 return *this;
478 // Return a new time modified by some delta.
479 Time operator+(TimeDelta delta) const {
480 return Time(delta.SaturatedAdd(us_));
482 Time operator-(TimeDelta delta) const {
483 return Time(-delta.SaturatedSub(us_));
486 // Comparison operators
487 bool operator==(Time other) const {
488 return us_ == other.us_;
490 bool operator!=(Time other) const {
491 return us_ != other.us_;
493 bool operator<(Time other) const {
494 return us_ < other.us_;
496 bool operator<=(Time other) const {
497 return us_ <= other.us_;
499 bool operator>(Time other) const {
500 return us_ > other.us_;
502 bool operator>=(Time other) const {
503 return us_ >= other.us_;
506 private:
507 friend class TimeDelta;
509 explicit Time(int64 us) : us_(us) {
512 // Explodes the given time to either local time |is_local = true| or UTC
513 // |is_local = false|.
514 void Explode(bool is_local, Exploded* exploded) const;
516 // Unexplodes a given time assuming the source is either local time
517 // |is_local = true| or UTC |is_local = false|.
518 static Time FromExploded(bool is_local, const Exploded& exploded);
520 // Converts a string representation of time to a Time object.
521 // An example of a time string which is converted is as below:-
522 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
523 // in the input string, local time |is_local = true| or
524 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
525 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
526 // timezone is not specified.
527 static bool FromStringInternal(const char* time_string,
528 bool is_local,
529 Time* parsed_time);
531 // Time in microseconds in UTC.
532 int64 us_;
535 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
537 // static
538 inline TimeDelta TimeDelta::FromDays(int days) {
539 // Preserve max to prevent overflow.
540 if (days == std::numeric_limits<int>::max())
541 return Max();
542 return TimeDelta(days * Time::kMicrosecondsPerDay);
545 // static
546 inline TimeDelta TimeDelta::FromHours(int hours) {
547 // Preserve max to prevent overflow.
548 if (hours == std::numeric_limits<int>::max())
549 return Max();
550 return TimeDelta(hours * Time::kMicrosecondsPerHour);
553 // static
554 inline TimeDelta TimeDelta::FromMinutes(int minutes) {
555 // Preserve max to prevent overflow.
556 if (minutes == std::numeric_limits<int>::max())
557 return Max();
558 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
561 // static
562 inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
563 // Preserve max to prevent overflow.
564 if (secs == std::numeric_limits<int64>::max())
565 return Max();
566 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
569 // static
570 inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
571 // Preserve max to prevent overflow.
572 if (ms == std::numeric_limits<int64>::max())
573 return Max();
574 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
577 // static
578 inline TimeDelta TimeDelta::FromSecondsD(double secs) {
579 // Preserve max to prevent overflow.
580 if (secs == std::numeric_limits<double>::infinity())
581 return Max();
582 return TimeDelta(static_cast<int64>(secs * Time::kMicrosecondsPerSecond));
585 // static
586 inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
587 // Preserve max to prevent overflow.
588 if (ms == std::numeric_limits<double>::infinity())
589 return Max();
590 return TimeDelta(static_cast<int64>(ms * Time::kMicrosecondsPerMillisecond));
593 // static
594 inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
595 // Preserve max to prevent overflow.
596 if (us == std::numeric_limits<int64>::max())
597 return Max();
598 return TimeDelta(us);
601 inline Time TimeDelta::operator+(Time t) const {
602 return Time(SaturatedAdd(t.us_));
605 // For logging use only.
606 BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
608 // TimeTicks ------------------------------------------------------------------
610 class BASE_EXPORT TimeTicks {
611 public:
612 // We define this even without OS_CHROMEOS for seccomp sandbox testing.
613 #if defined(OS_LINUX)
614 // Force definition of the system trace clock; it is a chromeos-only api
615 // at the moment and surfacing it in the right place requires mucking
616 // with glibc et al.
617 static const clockid_t kClockSystemTrace = 11;
618 #endif
620 TimeTicks() : ticks_(0) {
623 // Platform-dependent tick count representing "right now." When
624 // IsHighResolution() returns false, the resolution of the clock could be
625 // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
626 // microsecond.
627 static TimeTicks Now();
629 // Returns true if the high resolution clock is working on this system and
630 // Now() will return high resolution values. Note that, on systems where the
631 // high resolution clock works but is deemed inefficient, the low resolution
632 // clock will be used instead.
633 static bool IsHighResolution();
635 // Returns true if ThreadNow() is supported on this system.
636 static bool IsThreadNowSupported() {
637 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
638 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
639 return true;
640 #else
641 return false;
642 #endif
645 // Returns thread-specific CPU-time on systems that support this feature.
646 // Needs to be guarded with a call to IsThreadNowSupported(). Use this timer
647 // to (approximately) measure how much time the calling thread spent doing
648 // actual work vs. being de-scheduled. May return bogus results if the thread
649 // migrates to another CPU between two calls.
651 // WARNING: The returned value might NOT have the same origin as Now(). Do not
652 // perform math between TimeTicks values returned by Now() and ThreadNow() and
653 // expect meaningful results.
654 // TODO(miu): Since the timeline of these values is different, the values
655 // should be of a different type.
656 static TimeTicks ThreadNow();
658 // Returns the current system trace time or, if not available on this
659 // platform, a high-resolution time value; or a low-resolution time value if
660 // neither are avalable. On systems where a global trace clock is defined,
661 // timestamping TraceEvents's with this value guarantees synchronization
662 // between events collected inside chrome and events collected outside
663 // (e.g. kernel, X server).
665 // WARNING: The returned value might NOT have the same origin as Now(). Do not
666 // perform math between TimeTicks values returned by Now() and
667 // NowFromSystemTraceTime() and expect meaningful results.
668 // TODO(miu): Since the timeline of these values is different, the values
669 // should be of a different type.
670 static TimeTicks NowFromSystemTraceTime();
672 #if defined(OS_WIN)
673 // Translates an absolute QPC timestamp into a TimeTicks value. The returned
674 // value has the same origin as Now(). Do NOT attempt to use this if
675 // IsHighResolution() returns false.
676 static TimeTicks FromQPCValue(LONGLONG qpc_value);
677 #endif
679 // Returns true if this object has not been initialized.
680 bool is_null() const {
681 return ticks_ == 0;
684 // Returns true if the time delta is the maximum delta.
685 bool is_max() const {
686 return ticks_ == std::numeric_limits<int64>::max();
689 // Converts an integer value representing TimeTicks to a class. This is used
690 // when deserializing a |TimeTicks| structure, using a value known to be
691 // compatible. It is not provided as a constructor because the integer type
692 // may be unclear from the perspective of a caller.
693 static TimeTicks FromInternalValue(int64 ticks) {
694 return TimeTicks(ticks);
697 // Get the TimeTick value at the time of the UnixEpoch. This is useful when
698 // you need to relate the value of TimeTicks to a real time and date.
699 // Note: Upon first invocation, this function takes a snapshot of the realtime
700 // clock to establish a reference point. This function will return the same
701 // value for the duration of the application, but will be different in future
702 // application runs.
703 static TimeTicks UnixEpoch();
705 // Returns the internal numeric value of the TimeTicks object.
706 // For serializing, use FromInternalValue to reconstitute.
707 int64 ToInternalValue() const {
708 return ticks_;
711 // Returns |this| snapped to the next tick, given a |tick_phase| and
712 // repeating |tick_interval| in both directions. |this| may be before,
713 // after, or equal to the |tick_phase|.
714 TimeTicks SnappedToNextTick(TimeTicks tick_phase,
715 TimeDelta tick_interval) const;
717 TimeTicks& operator=(TimeTicks other) {
718 ticks_ = other.ticks_;
719 return *this;
722 // Compute the difference between two times.
723 TimeDelta operator-(TimeTicks other) const {
724 return TimeDelta(ticks_ - other.ticks_);
727 // Modify by some time delta.
728 TimeTicks& operator+=(TimeDelta delta) {
729 ticks_ = delta.SaturatedAdd(ticks_);
730 return *this;
732 TimeTicks& operator-=(TimeDelta delta) {
733 ticks_ = -delta.SaturatedSub(ticks_);
734 return *this;
737 // Return a new TimeTicks modified by some delta.
738 TimeTicks operator+(TimeDelta delta) const {
739 return TimeTicks(delta.SaturatedAdd(ticks_));
741 TimeTicks operator-(TimeDelta delta) const {
742 return TimeTicks(-delta.SaturatedSub(ticks_));
745 // Comparison operators
746 bool operator==(TimeTicks other) const {
747 return ticks_ == other.ticks_;
749 bool operator!=(TimeTicks other) const {
750 return ticks_ != other.ticks_;
752 bool operator<(TimeTicks other) const {
753 return ticks_ < other.ticks_;
755 bool operator<=(TimeTicks other) const {
756 return ticks_ <= other.ticks_;
758 bool operator>(TimeTicks other) const {
759 return ticks_ > other.ticks_;
761 bool operator>=(TimeTicks other) const {
762 return ticks_ >= other.ticks_;
765 protected:
766 friend class TimeDelta;
768 // Please use Now() to create a new object. This is for internal use
769 // and testing. Ticks is in microseconds.
770 explicit TimeTicks(int64 ticks) : ticks_(ticks) {
773 // Tick count in microseconds.
774 int64 ticks_;
776 #if defined(OS_WIN)
777 typedef DWORD (*TickFunctionType)(void);
778 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
779 #endif
782 inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
783 return TimeTicks(SaturatedAdd(t.ticks_));
786 // For logging use only.
787 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
789 } // namespace base
791 #endif // BASE_TIME_TIME_H_