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 time, internally represented as
6 // microseconds (s/1,000,000) since the Windows epoch (1601-01-01 00:00:00 UTC)
7 // (See http://crbug.com/14734). System-dependent clock interface routines are
8 // defined in time_PLATFORM.cc.
10 // TimeDelta represents a duration of time, internally represented in
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 #ifndef BASE_TIME_TIME_H_
24 #define BASE_TIME_TIME_H_
28 #include "base/base_export.h"
29 #include "base/basictypes.h"
30 #include "build/build_config.h"
32 #if defined(OS_MACOSX)
33 #include <CoreFoundation/CoreFoundation.h>
34 // Avoid Mac system header macro leak.
44 // For FILETIME in FromFileTime, until it moves to a new converter class.
45 // See TODO(iyengar) below.
56 // TimeDelta ------------------------------------------------------------------
58 class BASE_EXPORT TimeDelta {
60 TimeDelta() : delta_(0) {
63 // Converts units of time to TimeDeltas.
64 static TimeDelta FromDays(int days);
65 static TimeDelta FromHours(int hours);
66 static TimeDelta FromMinutes(int minutes);
67 static TimeDelta FromSeconds(int64 secs);
68 static TimeDelta FromMilliseconds(int64 ms);
69 static TimeDelta FromMicroseconds(int64 us);
71 static TimeDelta FromQPCValue(LONGLONG qpc_value);
74 // Converts an integer value representing TimeDelta to a class. This is used
75 // when deserializing a |TimeDelta| structure, using a value known to be
76 // compatible. It is not provided as a constructor because the integer type
77 // may be unclear from the perspective of a caller.
78 static TimeDelta FromInternalValue(int64 delta) {
79 return TimeDelta(delta);
82 // Returns the maximum time delta, which should be greater than any reasonable
83 // time delta we might compare it to. Adding or subtracting the maximum time
84 // delta to a time or another time delta has an undefined result.
85 static TimeDelta Max();
87 // Returns the internal numeric value of the TimeDelta object. Please don't
88 // use this and do arithmetic on it, as it is more error prone than using the
89 // provided operators.
90 // For serializing, use FromInternalValue to reconstitute.
91 int64 ToInternalValue() const {
95 // Returns true if the time delta is the maximum time delta.
97 return delta_ == std::numeric_limits<int64>::max();
100 #if defined(OS_POSIX)
101 struct timespec ToTimeSpec() const;
104 // Returns the time delta in some unit. The F versions return a floating
105 // point value, the "regular" versions return a rounded-down value.
107 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
108 // to the next full millisecond.
111 int InMinutes() const;
112 double InSecondsF() const;
113 int64 InSeconds() const;
114 double InMillisecondsF() const;
115 int64 InMilliseconds() const;
116 int64 InMillisecondsRoundedUp() const;
117 int64 InMicroseconds() const;
119 TimeDelta& operator=(TimeDelta other) {
120 delta_ = other.delta_;
124 // Computations with other deltas.
125 TimeDelta operator+(TimeDelta other) const {
126 return TimeDelta(delta_ + other.delta_);
128 TimeDelta operator-(TimeDelta other) const {
129 return TimeDelta(delta_ - other.delta_);
132 TimeDelta& operator+=(TimeDelta other) {
133 delta_ += other.delta_;
136 TimeDelta& operator-=(TimeDelta other) {
137 delta_ -= other.delta_;
140 TimeDelta operator-() const {
141 return TimeDelta(-delta_);
144 // Computations with ints, note that we only allow multiplicative operations
145 // with ints, and additive operations with other deltas.
146 TimeDelta operator*(int64 a) const {
147 return TimeDelta(delta_ * a);
149 TimeDelta operator/(int64 a) const {
150 return TimeDelta(delta_ / a);
152 TimeDelta& operator*=(int64 a) {
156 TimeDelta& operator/=(int64 a) {
160 int64 operator/(TimeDelta a) const {
161 return delta_ / a.delta_;
164 // Defined below because it depends on the definition of the other classes.
165 Time operator+(Time t) const;
166 TimeTicks operator+(TimeTicks t) const;
168 // Comparison operators.
169 bool operator==(TimeDelta other) const {
170 return delta_ == other.delta_;
172 bool operator!=(TimeDelta other) const {
173 return delta_ != other.delta_;
175 bool operator<(TimeDelta other) const {
176 return delta_ < other.delta_;
178 bool operator<=(TimeDelta other) const {
179 return delta_ <= other.delta_;
181 bool operator>(TimeDelta other) const {
182 return delta_ > other.delta_;
184 bool operator>=(TimeDelta other) const {
185 return delta_ >= other.delta_;
190 friend class TimeTicks;
191 friend TimeDelta operator*(int64 a, TimeDelta td);
193 // Constructs a delta given the duration in microseconds. This is private
194 // to avoid confusion by callers with an integer constructor. Use
195 // FromSeconds, FromMilliseconds, etc. instead.
196 explicit TimeDelta(int64 delta_us) : delta_(delta_us) {
199 // Delta in microseconds.
203 inline TimeDelta operator*(int64 a, TimeDelta td) {
204 return TimeDelta(a * td.delta_);
207 // Time -----------------------------------------------------------------------
209 // Represents a wall clock time.
210 class BASE_EXPORT Time {
212 static const int64 kMillisecondsPerSecond = 1000;
213 static const int64 kMicrosecondsPerMillisecond = 1000;
214 static const int64 kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
215 kMillisecondsPerSecond;
216 static const int64 kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
217 static const int64 kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
218 static const int64 kMicrosecondsPerDay = kMicrosecondsPerHour * 24;
219 static const int64 kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
220 static const int64 kNanosecondsPerMicrosecond = 1000;
221 static const int64 kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
222 kMicrosecondsPerSecond;
225 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
226 // the Posix delta of 1970. This is used for migrating between the old
227 // 1970-based epochs to the new 1601-based ones. It should be removed from
228 // this global header and put in the platform-specific ones when we remove the
230 static const int64 kWindowsEpochDeltaMicroseconds;
233 // Represents an exploded time that can be formatted nicely. This is kind of
234 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
235 // additions and changes to prevent errors.
236 struct BASE_EXPORT Exploded {
237 int year; // Four digit year "2007"
238 int month; // 1-based month (values 1 = January, etc.)
239 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
240 int day_of_month; // 1-based day of month (1-31)
241 int hour; // Hour within the current day (0-23)
242 int minute; // Minute within the current hour (0-59)
243 int second; // Second within the current minute (0-59 plus leap
244 // seconds which may take it up to 60).
245 int millisecond; // Milliseconds within the current second (0-999)
247 // A cursory test for whether the data members are within their
248 // respective ranges. A 'true' return value does not guarantee the
249 // Exploded value can be successfully converted to a Time value.
250 bool HasValidValues() const;
253 // Contains the NULL time. Use Time::Now() to get the current time.
257 // Returns true if the time object has not been initialized.
258 bool is_null() const {
262 // Returns true if the time object is the maximum time.
263 bool is_max() const {
264 return us_ == std::numeric_limits<int64>::max();
267 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
268 static Time UnixEpoch();
270 // Returns the current time. Watch out, the system might adjust its clock
271 // in which case time will actually go backwards. We don't guarantee that
272 // times are increasing, or that two calls to Now() won't be the same.
275 // Returns the maximum time, which should be greater than any reasonable time
276 // with which we might compare it.
279 // Returns the current time. Same as Now() except that this function always
280 // uses system time so that there are no discrepancies between the returned
281 // time and system time even on virtual environments including our test bot.
282 // For timing sensitive unittests, this function should be used.
283 static Time NowFromSystemTime();
285 // Converts to/from time_t in UTC and a Time class.
286 // TODO(brettw) this should be removed once everybody starts using the |Time|
288 static Time FromTimeT(time_t tt);
289 time_t ToTimeT() const;
291 // Converts time to/from a double which is the number of seconds since epoch
292 // (Jan 1, 1970). Webkit uses this format to represent time.
293 // Because WebKit initializes double time value to 0 to indicate "not
294 // initialized", we map it to empty Time object that also means "not
296 static Time FromDoubleT(double dt);
297 double ToDoubleT() const;
299 #if defined(OS_POSIX)
300 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
301 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
302 // having a 1 second resolution, which agrees with
303 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
304 static Time FromTimeSpec(const timespec& ts);
307 // Converts to/from the Javascript convention for times, a number of
308 // milliseconds since the epoch:
309 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
310 static Time FromJsTime(double ms_since_epoch);
311 double ToJsTime() const;
313 // Converts to Java convention for times, a number of
314 // milliseconds since the epoch.
315 int64 ToJavaTime() const;
317 #if defined(OS_POSIX)
318 static Time FromTimeVal(struct timeval t);
319 struct timeval ToTimeVal() const;
322 #if defined(OS_MACOSX)
323 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
324 CFAbsoluteTime ToCFAbsoluteTime() const;
328 static Time FromFileTime(FILETIME ft);
329 FILETIME ToFileTime() const;
331 // The minimum time of a low resolution timer. This is basically a windows
332 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
333 // treat it as static across all windows versions.
334 static const int kMinLowResolutionThresholdMs = 16;
336 // Enable or disable Windows high resolution timer. If the high resolution
337 // timer is not enabled, calls to ActivateHighResolutionTimer will fail.
338 // When disabling the high resolution timer, this function will not cause
339 // the high resolution timer to be deactivated, but will prevent future
341 // Must be called from the main thread.
342 // For more details see comments in time_win.cc.
343 static void EnableHighResolutionTimer(bool enable);
345 // Activates or deactivates the high resolution timer based on the |activate|
346 // flag. If the HighResolutionTimer is not Enabled (see
347 // EnableHighResolutionTimer), this function will return false. Otherwise
348 // returns true. Each successful activate call must be paired with a
349 // subsequent deactivate call.
350 // All callers to activate the high resolution timer must eventually call
351 // this function to deactivate the high resolution timer.
352 static bool ActivateHighResolutionTimer(bool activate);
354 // Returns true if the high resolution timer is both enabled and activated.
355 // This is provided for testing only, and is not tracked in a thread-safe
357 static bool IsHighResolutionTimerInUse();
360 // Converts an exploded structure representing either the local time or UTC
361 // into a Time class.
362 static Time FromUTCExploded(const Exploded& exploded) {
363 return FromExploded(false, exploded);
365 static Time FromLocalExploded(const Exploded& exploded) {
366 return FromExploded(true, exploded);
369 // Converts an integer value representing Time to a class. This is used
370 // when deserializing a |Time| structure, using a value known to be
371 // compatible. It is not provided as a constructor because the integer type
372 // may be unclear from the perspective of a caller.
373 static Time FromInternalValue(int64 us) {
377 // Converts a string representation of time to a Time object.
378 // An example of a time string which is converted is as below:-
379 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
380 // in the input string, FromString assumes local time and FromUTCString
381 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
382 // specified in RFC822) is treated as if the timezone is not specified.
383 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
384 // a new time converter class.
385 static bool FromString(const char* time_string, Time* parsed_time) {
386 return FromStringInternal(time_string, true, parsed_time);
388 static bool FromUTCString(const char* time_string, Time* parsed_time) {
389 return FromStringInternal(time_string, false, parsed_time);
392 // For serializing, use FromInternalValue to reconstitute. Please don't use
393 // this and do arithmetic on it, as it is more error prone than using the
394 // provided operators.
395 int64 ToInternalValue() const {
399 // Fills the given exploded structure with either the local time or UTC from
400 // this time structure (containing UTC).
401 void UTCExplode(Exploded* exploded) const {
402 return Explode(false, exploded);
404 void LocalExplode(Exploded* exploded) const {
405 return Explode(true, exploded);
408 // Rounds this time down to the nearest day in local time. It will represent
409 // midnight on that day.
410 Time LocalMidnight() const;
412 Time& operator=(Time other) {
417 // Compute the difference between two times.
418 TimeDelta operator-(Time other) const {
419 return TimeDelta(us_ - other.us_);
422 // Modify by some time delta.
423 Time& operator+=(TimeDelta delta) {
427 Time& operator-=(TimeDelta delta) {
432 // Return a new time modified by some delta.
433 Time operator+(TimeDelta delta) const {
434 return Time(us_ + delta.delta_);
436 Time operator-(TimeDelta delta) const {
437 return Time(us_ - delta.delta_);
440 // Comparison operators
441 bool operator==(Time other) const {
442 return us_ == other.us_;
444 bool operator!=(Time other) const {
445 return us_ != other.us_;
447 bool operator<(Time other) const {
448 return us_ < other.us_;
450 bool operator<=(Time other) const {
451 return us_ <= other.us_;
453 bool operator>(Time other) const {
454 return us_ > other.us_;
456 bool operator>=(Time other) const {
457 return us_ >= other.us_;
461 friend class TimeDelta;
463 explicit Time(int64 us) : us_(us) {
466 // Explodes the given time to either local time |is_local = true| or UTC
467 // |is_local = false|.
468 void Explode(bool is_local, Exploded* exploded) const;
470 // Unexplodes a given time assuming the source is either local time
471 // |is_local = true| or UTC |is_local = false|.
472 static Time FromExploded(bool is_local, const Exploded& exploded);
474 // Converts a string representation of time to a Time object.
475 // An example of a time string which is converted is as below:-
476 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
477 // in the input string, local time |is_local = true| or
478 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
479 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
480 // timezone is not specified.
481 static bool FromStringInternal(const char* time_string,
485 // The representation of Jan 1, 1970 UTC in microseconds since the
486 // platform-dependent epoch.
487 static const int64 kTimeTToMicrosecondsOffset;
490 // Indicates whether fast timers are usable right now. For instance,
491 // when using battery power, we might elect to prevent high speed timers
492 // which would draw more power.
493 static bool high_resolution_timer_enabled_;
494 // Count of activations on the high resolution timer. Only use in tests
495 // which are single threaded.
496 static int high_resolution_timer_activated_;
499 // Time in microseconds in UTC.
503 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
506 inline TimeDelta TimeDelta::FromDays(int days) {
507 // Preserve max to prevent overflow.
508 if (days == std::numeric_limits<int>::max())
510 return TimeDelta(days * Time::kMicrosecondsPerDay);
514 inline TimeDelta TimeDelta::FromHours(int hours) {
515 // Preserve max to prevent overflow.
516 if (hours == std::numeric_limits<int>::max())
518 return TimeDelta(hours * Time::kMicrosecondsPerHour);
522 inline TimeDelta TimeDelta::FromMinutes(int minutes) {
523 // Preserve max to prevent overflow.
524 if (minutes == std::numeric_limits<int>::max())
526 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
530 inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
531 // Preserve max to prevent overflow.
532 if (secs == std::numeric_limits<int64>::max())
534 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
538 inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
539 // Preserve max to prevent overflow.
540 if (ms == std::numeric_limits<int64>::max())
542 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
546 inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
547 // Preserve max to prevent overflow.
548 if (us == std::numeric_limits<int64>::max())
550 return TimeDelta(us);
553 inline Time TimeDelta::operator+(Time t) const {
554 return Time(t.us_ + delta_);
557 // TimeTicks ------------------------------------------------------------------
559 class BASE_EXPORT TimeTicks {
561 TimeTicks() : ticks_(0) {
564 // Platform-dependent tick count representing "right now."
565 // The resolution of this clock is ~1-15ms. Resolution varies depending
566 // on hardware/operating system configuration.
567 static TimeTicks Now();
569 // Returns a platform-dependent high-resolution tick count. Implementation
570 // is hardware dependent and may or may not return sub-millisecond
571 // resolution. THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND
572 // SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED.
573 static TimeTicks HighResNow();
575 static bool IsHighResNowFastAndReliable();
577 // Returns true if ThreadNow() is supported on this system.
578 static bool IsThreadNowSupported() {
579 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
580 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
587 // Returns thread-specific CPU-time on systems that support this feature.
588 // Needs to be guarded with a call to IsThreadNowSupported(). Use this timer
589 // to (approximately) measure how much time the calling thread spent doing
590 // actual work vs. being de-scheduled. May return bogus results if the thread
591 // migrates to another CPU between two calls.
592 static TimeTicks ThreadNow();
594 // Returns the current system trace time or, if none is defined, the current
595 // high-res time (i.e. HighResNow()). On systems where a global trace clock
596 // is defined, timestamping TraceEvents's with this value guarantees
597 // synchronization between events collected inside chrome and events
598 // collected outside (e.g. kernel, X server).
599 static TimeTicks NowFromSystemTraceTime();
602 // Get the absolute value of QPC time drift. For testing.
603 static int64 GetQPCDriftMicroseconds();
605 static TimeTicks FromQPCValue(LONGLONG qpc_value);
607 // Returns true if the high resolution clock is working on this system.
608 // This is only for testing.
609 static bool IsHighResClockWorking();
611 // Enable high resolution time for TimeTicks::Now(). This function will
612 // test for the availability of a working implementation of
613 // QueryPerformanceCounter(). If one is not available, this function does
614 // nothing and the resolution of Now() remains 1ms. Otherwise, all future
615 // calls to TimeTicks::Now() will have the higher resolution provided by QPC.
616 // Returns true if high resolution time was successfully enabled.
617 static bool SetNowIsHighResNowIfSupported();
619 // Returns a time value that is NOT rollover protected.
620 static TimeTicks UnprotectedNow();
623 // Returns true if this object has not been initialized.
624 bool is_null() const {
628 // Converts an integer value representing TimeTicks to a class. This is used
629 // when deserializing a |TimeTicks| structure, using a value known to be
630 // compatible. It is not provided as a constructor because the integer type
631 // may be unclear from the perspective of a caller.
632 static TimeTicks FromInternalValue(int64 ticks) {
633 return TimeTicks(ticks);
636 // Get the TimeTick value at the time of the UnixEpoch. This is useful when
637 // you need to relate the value of TimeTicks to a real time and date.
638 // Note: Upon first invocation, this function takes a snapshot of the realtime
639 // clock to establish a reference point. This function will return the same
640 // value for the duration of the application, but will be different in future
642 static TimeTicks UnixEpoch();
644 // Returns the internal numeric value of the TimeTicks object.
645 // For serializing, use FromInternalValue to reconstitute.
646 int64 ToInternalValue() const {
650 TimeTicks& operator=(TimeTicks other) {
651 ticks_ = other.ticks_;
655 // Compute the difference between two times.
656 TimeDelta operator-(TimeTicks other) const {
657 return TimeDelta(ticks_ - other.ticks_);
660 // Modify by some time delta.
661 TimeTicks& operator+=(TimeDelta delta) {
662 ticks_ += delta.delta_;
665 TimeTicks& operator-=(TimeDelta delta) {
666 ticks_ -= delta.delta_;
670 // Return a new TimeTicks modified by some delta.
671 TimeTicks operator+(TimeDelta delta) const {
672 return TimeTicks(ticks_ + delta.delta_);
674 TimeTicks operator-(TimeDelta delta) const {
675 return TimeTicks(ticks_ - delta.delta_);
678 // Comparison operators
679 bool operator==(TimeTicks other) const {
680 return ticks_ == other.ticks_;
682 bool operator!=(TimeTicks other) const {
683 return ticks_ != other.ticks_;
685 bool operator<(TimeTicks other) const {
686 return ticks_ < other.ticks_;
688 bool operator<=(TimeTicks other) const {
689 return ticks_ <= other.ticks_;
691 bool operator>(TimeTicks other) const {
692 return ticks_ > other.ticks_;
694 bool operator>=(TimeTicks other) const {
695 return ticks_ >= other.ticks_;
699 friend class TimeDelta;
701 // Please use Now() to create a new object. This is for internal use
702 // and testing. Ticks is in microseconds.
703 explicit TimeTicks(int64 ticks) : ticks_(ticks) {
706 // Tick count in microseconds.
710 typedef DWORD (*TickFunctionType)(void);
711 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
715 inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
716 return TimeTicks(t.ticks_ + delta_);
721 #endif // BASE_TIME_TIME_H_