Reland the ULONG -> SIZE_T change from 317177
[chromium-blink-merge.git] / base / time / time.h
blobb18c0b26d68c1bf8054b059278762fdc3491c62a
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 "build/build_config.h"
38 #if defined(OS_MACOSX)
39 #include <CoreFoundation/CoreFoundation.h>
40 // Avoid Mac system header macro leak.
41 #undef TYPE_BOOL
42 #endif
44 #if defined(OS_POSIX)
45 #include <unistd.h>
46 #include <sys/time.h>
47 #endif
49 #if defined(OS_WIN)
50 // For FILETIME in FromFileTime, until it moves to a new converter class.
51 // See TODO(iyengar) below.
52 #include <windows.h>
53 #endif
55 #include <limits>
57 namespace base {
59 class Time;
60 class TimeTicks;
62 // TimeDelta ------------------------------------------------------------------
64 class BASE_EXPORT TimeDelta {
65 public:
66 TimeDelta() : delta_(0) {
69 // Converts units of time to TimeDeltas.
70 static TimeDelta FromDays(int days);
71 static TimeDelta FromHours(int hours);
72 static TimeDelta FromMinutes(int minutes);
73 static TimeDelta FromSeconds(int64 secs);
74 static TimeDelta FromMilliseconds(int64 ms);
75 static TimeDelta FromSecondsD(double secs);
76 static TimeDelta FromMillisecondsD(double ms);
77 static TimeDelta FromMicroseconds(int64 us);
78 #if defined(OS_WIN)
79 static TimeDelta FromQPCValue(LONGLONG qpc_value);
80 #endif
82 // Converts an integer value representing TimeDelta to a class. This is used
83 // when deserializing a |TimeDelta| structure, using a value known to be
84 // compatible. It is not provided as a constructor because the integer type
85 // may be unclear from the perspective of a caller.
86 static TimeDelta FromInternalValue(int64 delta) {
87 return TimeDelta(delta);
90 // Returns the maximum time delta, which should be greater than any reasonable
91 // time delta we might compare it to. Adding or subtracting the maximum time
92 // delta to a time or another time delta has an undefined result.
93 static TimeDelta Max();
95 // Returns the internal numeric value of the TimeDelta object. Please don't
96 // use this and do arithmetic on it, as it is more error prone than using the
97 // provided operators.
98 // For serializing, use FromInternalValue to reconstitute.
99 int64 ToInternalValue() const {
100 return delta_;
103 // Returns the magnitude (absolute value) of this TimeDelta.
104 TimeDelta magnitude() const {
105 // Some toolchains provide an incomplete C++11 implementation and lack an
106 // int64 overload for std::abs(). The following is a simple branchless
107 // implementation:
108 const int64 mask = delta_ >> (sizeof(delta_) * 8 - 1);
109 return TimeDelta((delta_ + mask) ^ mask);
112 // Returns true if the time delta is the maximum time delta.
113 bool is_max() const {
114 return delta_ == std::numeric_limits<int64>::max();
117 #if defined(OS_POSIX)
118 struct timespec ToTimeSpec() const;
119 #endif
121 // Returns the time delta in some unit. The F versions return a floating
122 // point value, the "regular" versions return a rounded-down value.
124 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
125 // to the next full millisecond.
126 int InDays() const;
127 int InHours() const;
128 int InMinutes() const;
129 double InSecondsF() const;
130 int64 InSeconds() const;
131 double InMillisecondsF() const;
132 int64 InMilliseconds() const;
133 int64 InMillisecondsRoundedUp() const;
134 int64 InMicroseconds() const;
136 TimeDelta& operator=(TimeDelta other) {
137 delta_ = other.delta_;
138 return *this;
141 // Computations with other deltas.
142 TimeDelta operator+(TimeDelta other) const {
143 return TimeDelta(delta_ + other.delta_);
145 TimeDelta operator-(TimeDelta other) const {
146 return TimeDelta(delta_ - other.delta_);
149 TimeDelta& operator+=(TimeDelta other) {
150 delta_ += other.delta_;
151 return *this;
153 TimeDelta& operator-=(TimeDelta other) {
154 delta_ -= other.delta_;
155 return *this;
157 TimeDelta operator-() const {
158 return TimeDelta(-delta_);
161 // Computations with numeric types.
162 template<typename T>
163 TimeDelta operator*(T a) const {
164 return TimeDelta(delta_ * a);
166 template<typename T>
167 TimeDelta operator/(T a) const {
168 return TimeDelta(delta_ / a);
170 template<typename T>
171 TimeDelta& operator*=(T a) {
172 delta_ *= a;
173 return *this;
175 template<typename T>
176 TimeDelta& operator/=(T a) {
177 delta_ /= a;
178 return *this;
181 int64 operator/(TimeDelta a) const {
182 return delta_ / a.delta_;
185 // Defined below because it depends on the definition of the other classes.
186 Time operator+(Time t) const;
187 TimeTicks operator+(TimeTicks t) const;
189 // Comparison operators.
190 bool operator==(TimeDelta other) const {
191 return delta_ == other.delta_;
193 bool operator!=(TimeDelta other) const {
194 return delta_ != other.delta_;
196 bool operator<(TimeDelta other) const {
197 return delta_ < other.delta_;
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_;
209 private:
210 friend class Time;
211 friend class TimeTicks;
213 // Constructs a delta given the duration in microseconds. This is private
214 // to avoid confusion by callers with an integer constructor. Use
215 // FromSeconds, FromMilliseconds, etc. instead.
216 explicit TimeDelta(int64 delta_us) : delta_(delta_us) {
219 // Delta in microseconds.
220 int64 delta_;
223 template<typename T>
224 inline TimeDelta operator*(T a, TimeDelta td) {
225 return td * a;
228 // For logging use only.
229 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
231 // Time -----------------------------------------------------------------------
233 // Represents a wall clock time in UTC.
234 class BASE_EXPORT Time {
235 public:
236 static const int64 kMillisecondsPerSecond = 1000;
237 static const int64 kMicrosecondsPerMillisecond = 1000;
238 static const int64 kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
239 kMillisecondsPerSecond;
240 static const int64 kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
241 static const int64 kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
242 static const int64 kMicrosecondsPerDay = kMicrosecondsPerHour * 24;
243 static const int64 kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
244 static const int64 kNanosecondsPerMicrosecond = 1000;
245 static const int64 kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
246 kMicrosecondsPerSecond;
248 // The representation of Jan 1, 1970 UTC in microseconds since the
249 // platform-dependent epoch.
250 static const int64 kTimeTToMicrosecondsOffset;
252 #if !defined(OS_WIN)
253 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
254 // the Posix delta of 1970. This is used for migrating between the old
255 // 1970-based epochs to the new 1601-based ones. It should be removed from
256 // this global header and put in the platform-specific ones when we remove the
257 // migration code.
258 static const int64 kWindowsEpochDeltaMicroseconds;
259 #else
260 // To avoid overflow in QPC to Microseconds calculations, since we multiply
261 // by kMicrosecondsPerSecond, then the QPC value should not exceed
262 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
263 static const int64 kQPCOverflowThreshold = 0x8637BD05AF7;
264 #endif
266 // Represents an exploded time that can be formatted nicely. This is kind of
267 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
268 // additions and changes to prevent errors.
269 struct BASE_EXPORT Exploded {
270 int year; // Four digit year "2007"
271 int month; // 1-based month (values 1 = January, etc.)
272 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
273 int day_of_month; // 1-based day of month (1-31)
274 int hour; // Hour within the current day (0-23)
275 int minute; // Minute within the current hour (0-59)
276 int second; // Second within the current minute (0-59 plus leap
277 // seconds which may take it up to 60).
278 int millisecond; // Milliseconds within the current second (0-999)
280 // A cursory test for whether the data members are within their
281 // respective ranges. A 'true' return value does not guarantee the
282 // Exploded value can be successfully converted to a Time value.
283 bool HasValidValues() const;
286 // Contains the NULL time. Use Time::Now() to get the current time.
287 Time() : us_(0) {
290 // Returns true if the time object has not been initialized.
291 bool is_null() const {
292 return us_ == 0;
295 // Returns true if the time object is the maximum time.
296 bool is_max() const {
297 return us_ == std::numeric_limits<int64>::max();
300 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
301 static Time UnixEpoch();
303 // Returns the current time. Watch out, the system might adjust its clock
304 // in which case time will actually go backwards. We don't guarantee that
305 // times are increasing, or that two calls to Now() won't be the same.
306 static Time Now();
308 // Returns the maximum time, which should be greater than any reasonable time
309 // with which we might compare it.
310 static Time Max();
312 // Returns the current time. Same as Now() except that this function always
313 // uses system time so that there are no discrepancies between the returned
314 // time and system time even on virtual environments including our test bot.
315 // For timing sensitive unittests, this function should be used.
316 static Time NowFromSystemTime();
318 // Converts to/from time_t in UTC and a Time class.
319 // TODO(brettw) this should be removed once everybody starts using the |Time|
320 // class.
321 static Time FromTimeT(time_t tt);
322 time_t ToTimeT() const;
324 // Converts time to/from a double which is the number of seconds since epoch
325 // (Jan 1, 1970). Webkit uses this format to represent time.
326 // Because WebKit initializes double time value to 0 to indicate "not
327 // initialized", we map it to empty Time object that also means "not
328 // initialized".
329 static Time FromDoubleT(double dt);
330 double ToDoubleT() const;
332 #if defined(OS_POSIX)
333 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
334 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
335 // having a 1 second resolution, which agrees with
336 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
337 static Time FromTimeSpec(const timespec& ts);
338 #endif
340 // Converts to/from the Javascript convention for times, a number of
341 // milliseconds since the epoch:
342 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
343 static Time FromJsTime(double ms_since_epoch);
344 double ToJsTime() const;
346 // Converts to Java convention for times, a number of
347 // milliseconds since the epoch.
348 int64 ToJavaTime() const;
350 #if defined(OS_POSIX)
351 static Time FromTimeVal(struct timeval t);
352 struct timeval ToTimeVal() const;
353 #endif
355 #if defined(OS_MACOSX)
356 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
357 CFAbsoluteTime ToCFAbsoluteTime() const;
358 #endif
360 #if defined(OS_WIN)
361 static Time FromFileTime(FILETIME ft);
362 FILETIME ToFileTime() const;
364 // The minimum time of a low resolution timer. This is basically a windows
365 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
366 // treat it as static across all windows versions.
367 static const int kMinLowResolutionThresholdMs = 16;
369 // Enable or disable Windows high resolution timer.
370 static void EnableHighResolutionTimer(bool enable);
372 // Activates or deactivates the high resolution timer based on the |activate|
373 // flag. If the HighResolutionTimer is not Enabled (see
374 // EnableHighResolutionTimer), this function will return false. Otherwise
375 // returns true. Each successful activate call must be paired with a
376 // subsequent deactivate call.
377 // All callers to activate the high resolution timer must eventually call
378 // this function to deactivate the high resolution timer.
379 static bool ActivateHighResolutionTimer(bool activate);
381 // Returns true if the high resolution timer is both enabled and activated.
382 // This is provided for testing only, and is not tracked in a thread-safe
383 // way.
384 static bool IsHighResolutionTimerInUse();
385 #endif
387 // Converts an exploded structure representing either the local time or UTC
388 // into a Time class.
389 static Time FromUTCExploded(const Exploded& exploded) {
390 return FromExploded(false, exploded);
392 static Time FromLocalExploded(const Exploded& exploded) {
393 return FromExploded(true, exploded);
396 // Converts an integer value representing Time to a class. This is used
397 // when deserializing a |Time| structure, using a value known to be
398 // compatible. It is not provided as a constructor because the integer type
399 // may be unclear from the perspective of a caller.
400 static Time FromInternalValue(int64 us) {
401 return Time(us);
404 // Converts a string representation of time to a Time object.
405 // An example of a time string which is converted is as below:-
406 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
407 // in the input string, FromString assumes local time and FromUTCString
408 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
409 // specified in RFC822) is treated as if the timezone is not specified.
410 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
411 // a new time converter class.
412 static bool FromString(const char* time_string, Time* parsed_time) {
413 return FromStringInternal(time_string, true, parsed_time);
415 static bool FromUTCString(const char* time_string, Time* parsed_time) {
416 return FromStringInternal(time_string, false, parsed_time);
419 // For serializing, use FromInternalValue to reconstitute. Please don't use
420 // this and do arithmetic on it, as it is more error prone than using the
421 // provided operators.
422 int64 ToInternalValue() const {
423 return us_;
426 // Fills the given exploded structure with either the local time or UTC from
427 // this time structure (containing UTC).
428 void UTCExplode(Exploded* exploded) const {
429 return Explode(false, exploded);
431 void LocalExplode(Exploded* exploded) const {
432 return Explode(true, exploded);
435 // Rounds this time down to the nearest day in local time. It will represent
436 // midnight on that day.
437 Time LocalMidnight() const;
439 Time& operator=(Time other) {
440 us_ = other.us_;
441 return *this;
444 // Compute the difference between two times.
445 TimeDelta operator-(Time other) const {
446 return TimeDelta(us_ - other.us_);
449 // Modify by some time delta.
450 Time& operator+=(TimeDelta delta) {
451 us_ += delta.delta_;
452 return *this;
454 Time& operator-=(TimeDelta delta) {
455 us_ -= delta.delta_;
456 return *this;
459 // Return a new time modified by some delta.
460 Time operator+(TimeDelta delta) const {
461 return Time(us_ + delta.delta_);
463 Time operator-(TimeDelta delta) const {
464 return Time(us_ - delta.delta_);
467 // Comparison operators
468 bool operator==(Time other) const {
469 return us_ == other.us_;
471 bool operator!=(Time other) const {
472 return us_ != other.us_;
474 bool operator<(Time other) const {
475 return us_ < other.us_;
477 bool operator<=(Time other) const {
478 return us_ <= other.us_;
480 bool operator>(Time other) const {
481 return us_ > other.us_;
483 bool operator>=(Time other) const {
484 return us_ >= other.us_;
487 private:
488 friend class TimeDelta;
490 explicit Time(int64 us) : us_(us) {
493 // Explodes the given time to either local time |is_local = true| or UTC
494 // |is_local = false|.
495 void Explode(bool is_local, Exploded* exploded) const;
497 // Unexplodes a given time assuming the source is either local time
498 // |is_local = true| or UTC |is_local = false|.
499 static Time FromExploded(bool is_local, const Exploded& exploded);
501 // Converts a string representation of time to a Time object.
502 // An example of a time string which is converted is as below:-
503 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
504 // in the input string, local time |is_local = true| or
505 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
506 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
507 // timezone is not specified.
508 static bool FromStringInternal(const char* time_string,
509 bool is_local,
510 Time* parsed_time);
512 // Time in microseconds in UTC.
513 int64 us_;
516 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
518 // static
519 inline TimeDelta TimeDelta::FromDays(int days) {
520 // Preserve max to prevent overflow.
521 if (days == std::numeric_limits<int>::max())
522 return Max();
523 return TimeDelta(days * Time::kMicrosecondsPerDay);
526 // static
527 inline TimeDelta TimeDelta::FromHours(int hours) {
528 // Preserve max to prevent overflow.
529 if (hours == std::numeric_limits<int>::max())
530 return Max();
531 return TimeDelta(hours * Time::kMicrosecondsPerHour);
534 // static
535 inline TimeDelta TimeDelta::FromMinutes(int minutes) {
536 // Preserve max to prevent overflow.
537 if (minutes == std::numeric_limits<int>::max())
538 return Max();
539 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
542 // static
543 inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
544 // Preserve max to prevent overflow.
545 if (secs == std::numeric_limits<int64>::max())
546 return Max();
547 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
550 // static
551 inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
552 // Preserve max to prevent overflow.
553 if (ms == std::numeric_limits<int64>::max())
554 return Max();
555 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
558 // static
559 inline TimeDelta TimeDelta::FromSecondsD(double secs) {
560 // Preserve max to prevent overflow.
561 if (secs == std::numeric_limits<double>::infinity())
562 return Max();
563 return TimeDelta(static_cast<int64>(secs * Time::kMicrosecondsPerSecond));
566 // static
567 inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
568 // Preserve max to prevent overflow.
569 if (ms == std::numeric_limits<double>::infinity())
570 return Max();
571 return TimeDelta(static_cast<int64>(ms * Time::kMicrosecondsPerMillisecond));
574 // static
575 inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
576 // Preserve max to prevent overflow.
577 if (us == std::numeric_limits<int64>::max())
578 return Max();
579 return TimeDelta(us);
582 inline Time TimeDelta::operator+(Time t) const {
583 return Time(t.us_ + delta_);
586 // For logging use only.
587 BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
589 // TimeTicks ------------------------------------------------------------------
591 class BASE_EXPORT TimeTicks {
592 public:
593 // We define this even without OS_CHROMEOS for seccomp sandbox testing.
594 #if defined(OS_LINUX)
595 // Force definition of the system trace clock; it is a chromeos-only api
596 // at the moment and surfacing it in the right place requires mucking
597 // with glibc et al.
598 static const clockid_t kClockSystemTrace = 11;
599 #endif
601 TimeTicks() : ticks_(0) {
604 // Platform-dependent tick count representing "right now." When
605 // IsHighResolution() returns false, the resolution of the clock could be
606 // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
607 // microsecond.
608 static TimeTicks Now();
610 // Returns true if the high resolution clock is working on this system and
611 // Now() will return high resolution values. Note that, on systems where the
612 // high resolution clock works but is deemed inefficient, the low resolution
613 // clock will be used instead.
614 static bool IsHighResolution();
616 // Returns true if ThreadNow() is supported on this system.
617 static bool IsThreadNowSupported() {
618 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
619 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
620 return true;
621 #else
622 return false;
623 #endif
626 // Returns thread-specific CPU-time on systems that support this feature.
627 // Needs to be guarded with a call to IsThreadNowSupported(). Use this timer
628 // to (approximately) measure how much time the calling thread spent doing
629 // actual work vs. being de-scheduled. May return bogus results if the thread
630 // migrates to another CPU between two calls.
632 // WARNING: The returned value might NOT have the same origin as Now(). Do not
633 // perform math between TimeTicks values returned by Now() and ThreadNow() and
634 // expect meaningful results.
635 // TODO(miu): Since the timeline of these values is different, the values
636 // should be of a different type.
637 static TimeTicks ThreadNow();
639 // Returns the current system trace time or, if not available on this
640 // platform, a high-resolution time value; or a low-resolution time value if
641 // neither are avalable. On systems where a global trace clock is defined,
642 // timestamping TraceEvents's with this value guarantees synchronization
643 // between events collected inside chrome and events collected outside
644 // (e.g. kernel, X server).
646 // WARNING: The returned value might NOT have the same origin as Now(). Do not
647 // perform math between TimeTicks values returned by Now() and
648 // NowFromSystemTraceTime() and expect meaningful results.
649 // TODO(miu): Since the timeline of these values is different, the values
650 // should be of a different type.
651 static TimeTicks NowFromSystemTraceTime();
653 #if defined(OS_WIN)
654 // Translates an absolute QPC timestamp into a TimeTicks value. The returned
655 // value has the same origin as Now(). Do NOT attempt to use this if
656 // IsHighResolution() returns false.
657 static TimeTicks FromQPCValue(LONGLONG qpc_value);
658 #endif
660 // Returns true if this object has not been initialized.
661 bool is_null() const {
662 return ticks_ == 0;
665 // Converts an integer value representing TimeTicks to a class. This is used
666 // when deserializing a |TimeTicks| structure, using a value known to be
667 // compatible. It is not provided as a constructor because the integer type
668 // may be unclear from the perspective of a caller.
669 static TimeTicks FromInternalValue(int64 ticks) {
670 return TimeTicks(ticks);
673 // Get the TimeTick value at the time of the UnixEpoch. This is useful when
674 // you need to relate the value of TimeTicks to a real time and date.
675 // Note: Upon first invocation, this function takes a snapshot of the realtime
676 // clock to establish a reference point. This function will return the same
677 // value for the duration of the application, but will be different in future
678 // application runs.
679 static TimeTicks UnixEpoch();
681 // Returns the internal numeric value of the TimeTicks object.
682 // For serializing, use FromInternalValue to reconstitute.
683 int64 ToInternalValue() const {
684 return ticks_;
687 // Returns |this| snapped to the next tick, given a |tick_phase| and
688 // repeating |tick_interval| in both directions. |this| may be before,
689 // after, or equal to the |tick_phase|.
690 TimeTicks SnappedToNextTick(TimeTicks tick_phase,
691 TimeDelta tick_interval) const;
693 TimeTicks& operator=(TimeTicks other) {
694 ticks_ = other.ticks_;
695 return *this;
698 // Compute the difference between two times.
699 TimeDelta operator-(TimeTicks other) const {
700 return TimeDelta(ticks_ - other.ticks_);
703 // Modify by some time delta.
704 TimeTicks& operator+=(TimeDelta delta) {
705 ticks_ += delta.delta_;
706 return *this;
708 TimeTicks& operator-=(TimeDelta delta) {
709 ticks_ -= delta.delta_;
710 return *this;
713 // Return a new TimeTicks modified by some delta.
714 TimeTicks operator+(TimeDelta delta) const {
715 return TimeTicks(ticks_ + delta.delta_);
717 TimeTicks operator-(TimeDelta delta) const {
718 return TimeTicks(ticks_ - delta.delta_);
721 // Comparison operators
722 bool operator==(TimeTicks other) const {
723 return ticks_ == other.ticks_;
725 bool operator!=(TimeTicks other) const {
726 return ticks_ != other.ticks_;
728 bool operator<(TimeTicks other) const {
729 return ticks_ < other.ticks_;
731 bool operator<=(TimeTicks other) const {
732 return ticks_ <= other.ticks_;
734 bool operator>(TimeTicks other) const {
735 return ticks_ > other.ticks_;
737 bool operator>=(TimeTicks other) const {
738 return ticks_ >= other.ticks_;
741 protected:
742 friend class TimeDelta;
744 // Please use Now() to create a new object. This is for internal use
745 // and testing. Ticks is in microseconds.
746 explicit TimeTicks(int64 ticks) : ticks_(ticks) {
749 // Tick count in microseconds.
750 int64 ticks_;
752 #if defined(OS_WIN)
753 typedef DWORD (*TickFunctionType)(void);
754 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
755 #endif
758 inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
759 return TimeTicks(t.ticks_ + delta_);
762 // For logging use only.
763 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
765 } // namespace base
767 #endif // BASE_TIME_TIME_H_