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.
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 // 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_
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.
50 // For FILETIME in FromFileTime, until it moves to a new converter class.
51 // See TODO(iyengar) below.
62 // TimeDelta ------------------------------------------------------------------
64 class BASE_EXPORT TimeDelta
{
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
);
79 static TimeDelta
FromQPCValue(LONGLONG qpc_value
);
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 {
103 // Returns true if the time delta is the maximum time delta.
104 bool is_max() const {
105 return delta_
== std::numeric_limits
<int64
>::max();
108 #if defined(OS_POSIX)
109 struct timespec
ToTimeSpec() const;
112 // Returns the time delta in some unit. The F versions return a floating
113 // point value, the "regular" versions return a rounded-down value.
115 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
116 // to the next full millisecond.
119 int InMinutes() const;
120 double InSecondsF() const;
121 int64
InSeconds() const;
122 double InMillisecondsF() const;
123 int64
InMilliseconds() const;
124 int64
InMillisecondsRoundedUp() const;
125 int64
InMicroseconds() const;
127 TimeDelta
& operator=(TimeDelta other
) {
128 delta_
= other
.delta_
;
132 // Computations with other deltas.
133 TimeDelta
operator+(TimeDelta other
) const {
134 return TimeDelta(delta_
+ other
.delta_
);
136 TimeDelta
operator-(TimeDelta other
) const {
137 return TimeDelta(delta_
- other
.delta_
);
140 TimeDelta
& operator+=(TimeDelta other
) {
141 delta_
+= other
.delta_
;
144 TimeDelta
& operator-=(TimeDelta other
) {
145 delta_
-= other
.delta_
;
148 TimeDelta
operator-() const {
149 return TimeDelta(-delta_
);
152 // Computations with ints, note that we only allow multiplicative operations
153 // with ints, and additive operations with other deltas.
154 TimeDelta
operator*(int64 a
) const {
155 return TimeDelta(delta_
* a
);
157 TimeDelta
operator/(int64 a
) const {
158 return TimeDelta(delta_
/ a
);
160 TimeDelta
& operator*=(int64 a
) {
164 TimeDelta
& operator/=(int64 a
) {
168 int64
operator/(TimeDelta a
) const {
169 return delta_
/ a
.delta_
;
172 // Defined below because it depends on the definition of the other classes.
173 Time
operator+(Time t
) const;
174 TimeTicks
operator+(TimeTicks t
) const;
176 // Comparison operators.
177 bool operator==(TimeDelta other
) const {
178 return delta_
== other
.delta_
;
180 bool operator!=(TimeDelta other
) const {
181 return delta_
!= other
.delta_
;
183 bool operator<(TimeDelta other
) const {
184 return delta_
< other
.delta_
;
186 bool operator<=(TimeDelta other
) const {
187 return delta_
<= other
.delta_
;
189 bool operator>(TimeDelta other
) const {
190 return delta_
> other
.delta_
;
192 bool operator>=(TimeDelta other
) const {
193 return delta_
>= other
.delta_
;
198 friend class TimeTicks
;
199 friend TimeDelta
operator*(int64 a
, TimeDelta td
);
201 // Constructs a delta given the duration in microseconds. This is private
202 // to avoid confusion by callers with an integer constructor. Use
203 // FromSeconds, FromMilliseconds, etc. instead.
204 explicit TimeDelta(int64 delta_us
) : delta_(delta_us
) {
207 // Delta in microseconds.
211 inline TimeDelta
operator*(int64 a
, TimeDelta td
) {
212 return TimeDelta(a
* td
.delta_
);
215 // For logging use only.
216 BASE_EXPORT
std::ostream
& operator<<(std::ostream
& os
, TimeDelta time_delta
);
218 // Time -----------------------------------------------------------------------
220 // Represents a wall clock time in UTC.
221 class BASE_EXPORT Time
{
223 static const int64 kMillisecondsPerSecond
= 1000;
224 static const int64 kMicrosecondsPerMillisecond
= 1000;
225 static const int64 kMicrosecondsPerSecond
= kMicrosecondsPerMillisecond
*
226 kMillisecondsPerSecond
;
227 static const int64 kMicrosecondsPerMinute
= kMicrosecondsPerSecond
* 60;
228 static const int64 kMicrosecondsPerHour
= kMicrosecondsPerMinute
* 60;
229 static const int64 kMicrosecondsPerDay
= kMicrosecondsPerHour
* 24;
230 static const int64 kMicrosecondsPerWeek
= kMicrosecondsPerDay
* 7;
231 static const int64 kNanosecondsPerMicrosecond
= 1000;
232 static const int64 kNanosecondsPerSecond
= kNanosecondsPerMicrosecond
*
233 kMicrosecondsPerSecond
;
236 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
237 // the Posix delta of 1970. This is used for migrating between the old
238 // 1970-based epochs to the new 1601-based ones. It should be removed from
239 // this global header and put in the platform-specific ones when we remove the
241 static const int64 kWindowsEpochDeltaMicroseconds
;
243 // To avoid overflow in QPC to Microseconds calculations, since we multiply
244 // by kMicrosecondsPerSecond, then the QPC value should not exceed
245 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
246 static const int64 kQPCOverflowThreshold
= 0x8637BD05AF7;
249 // Represents an exploded time that can be formatted nicely. This is kind of
250 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
251 // additions and changes to prevent errors.
252 struct BASE_EXPORT Exploded
{
253 int year
; // Four digit year "2007"
254 int month
; // 1-based month (values 1 = January, etc.)
255 int day_of_week
; // 0-based day of week (0 = Sunday, etc.)
256 int day_of_month
; // 1-based day of month (1-31)
257 int hour
; // Hour within the current day (0-23)
258 int minute
; // Minute within the current hour (0-59)
259 int second
; // Second within the current minute (0-59 plus leap
260 // seconds which may take it up to 60).
261 int millisecond
; // Milliseconds within the current second (0-999)
263 // A cursory test for whether the data members are within their
264 // respective ranges. A 'true' return value does not guarantee the
265 // Exploded value can be successfully converted to a Time value.
266 bool HasValidValues() const;
269 // Contains the NULL time. Use Time::Now() to get the current time.
273 // Returns true if the time object has not been initialized.
274 bool is_null() const {
278 // Returns true if the time object is the maximum time.
279 bool is_max() const {
280 return us_
== std::numeric_limits
<int64
>::max();
283 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
284 static Time
UnixEpoch();
286 // Returns the current time. Watch out, the system might adjust its clock
287 // in which case time will actually go backwards. We don't guarantee that
288 // times are increasing, or that two calls to Now() won't be the same.
291 // Returns the maximum time, which should be greater than any reasonable time
292 // with which we might compare it.
295 // Returns the current time. Same as Now() except that this function always
296 // uses system time so that there are no discrepancies between the returned
297 // time and system time even on virtual environments including our test bot.
298 // For timing sensitive unittests, this function should be used.
299 static Time
NowFromSystemTime();
301 // Converts to/from time_t in UTC and a Time class.
302 // TODO(brettw) this should be removed once everybody starts using the |Time|
304 static Time
FromTimeT(time_t tt
);
305 time_t ToTimeT() const;
307 // Converts time to/from a double which is the number of seconds since epoch
308 // (Jan 1, 1970). Webkit uses this format to represent time.
309 // Because WebKit initializes double time value to 0 to indicate "not
310 // initialized", we map it to empty Time object that also means "not
312 static Time
FromDoubleT(double dt
);
313 double ToDoubleT() const;
315 #if defined(OS_POSIX)
316 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
317 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
318 // having a 1 second resolution, which agrees with
319 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
320 static Time
FromTimeSpec(const timespec
& ts
);
323 // Converts to/from the Javascript convention for times, a number of
324 // milliseconds since the epoch:
325 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
326 static Time
FromJsTime(double ms_since_epoch
);
327 double ToJsTime() const;
329 // Converts to Java convention for times, a number of
330 // milliseconds since the epoch.
331 int64
ToJavaTime() const;
333 #if defined(OS_POSIX)
334 static Time
FromTimeVal(struct timeval t
);
335 struct timeval
ToTimeVal() const;
338 #if defined(OS_MACOSX)
339 static Time
FromCFAbsoluteTime(CFAbsoluteTime t
);
340 CFAbsoluteTime
ToCFAbsoluteTime() const;
344 static Time
FromFileTime(FILETIME ft
);
345 FILETIME
ToFileTime() const;
347 // The minimum time of a low resolution timer. This is basically a windows
348 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
349 // treat it as static across all windows versions.
350 static const int kMinLowResolutionThresholdMs
= 16;
352 // Enable or disable Windows high resolution timer.
353 static void EnableHighResolutionTimer(bool enable
);
355 // Activates or deactivates the high resolution timer based on the |activate|
356 // flag. If the HighResolutionTimer is not Enabled (see
357 // EnableHighResolutionTimer), this function will return false. Otherwise
358 // returns true. Each successful activate call must be paired with a
359 // subsequent deactivate call.
360 // All callers to activate the high resolution timer must eventually call
361 // this function to deactivate the high resolution timer.
362 static bool ActivateHighResolutionTimer(bool activate
);
364 // Returns true if the high resolution timer is both enabled and activated.
365 // This is provided for testing only, and is not tracked in a thread-safe
367 static bool IsHighResolutionTimerInUse();
370 // Converts an exploded structure representing either the local time or UTC
371 // into a Time class.
372 static Time
FromUTCExploded(const Exploded
& exploded
) {
373 return FromExploded(false, exploded
);
375 static Time
FromLocalExploded(const Exploded
& exploded
) {
376 return FromExploded(true, exploded
);
379 // Converts an integer value representing Time to a class. This is used
380 // when deserializing a |Time| structure, using a value known to be
381 // compatible. It is not provided as a constructor because the integer type
382 // may be unclear from the perspective of a caller.
383 static Time
FromInternalValue(int64 us
) {
387 // Converts a string representation of time to a Time object.
388 // An example of a time string which is converted is as below:-
389 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
390 // in the input string, FromString assumes local time and FromUTCString
391 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
392 // specified in RFC822) is treated as if the timezone is not specified.
393 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
394 // a new time converter class.
395 static bool FromString(const char* time_string
, Time
* parsed_time
) {
396 return FromStringInternal(time_string
, true, parsed_time
);
398 static bool FromUTCString(const char* time_string
, Time
* parsed_time
) {
399 return FromStringInternal(time_string
, false, parsed_time
);
402 // For serializing, use FromInternalValue to reconstitute. Please don't use
403 // this and do arithmetic on it, as it is more error prone than using the
404 // provided operators.
405 int64
ToInternalValue() const {
409 // Fills the given exploded structure with either the local time or UTC from
410 // this time structure (containing UTC).
411 void UTCExplode(Exploded
* exploded
) const {
412 return Explode(false, exploded
);
414 void LocalExplode(Exploded
* exploded
) const {
415 return Explode(true, exploded
);
418 // Rounds this time down to the nearest day in local time. It will represent
419 // midnight on that day.
420 Time
LocalMidnight() const;
422 Time
& operator=(Time other
) {
427 // Compute the difference between two times.
428 TimeDelta
operator-(Time other
) const {
429 return TimeDelta(us_
- other
.us_
);
432 // Modify by some time delta.
433 Time
& operator+=(TimeDelta delta
) {
437 Time
& operator-=(TimeDelta delta
) {
442 // Return a new time modified by some delta.
443 Time
operator+(TimeDelta delta
) const {
444 return Time(us_
+ delta
.delta_
);
446 Time
operator-(TimeDelta delta
) const {
447 return Time(us_
- delta
.delta_
);
450 // Comparison operators
451 bool operator==(Time other
) const {
452 return us_
== other
.us_
;
454 bool operator!=(Time other
) const {
455 return us_
!= other
.us_
;
457 bool operator<(Time other
) const {
458 return us_
< other
.us_
;
460 bool operator<=(Time other
) const {
461 return us_
<= other
.us_
;
463 bool operator>(Time other
) const {
464 return us_
> other
.us_
;
466 bool operator>=(Time other
) const {
467 return us_
>= other
.us_
;
471 friend class TimeDelta
;
473 explicit Time(int64 us
) : us_(us
) {
476 // Explodes the given time to either local time |is_local = true| or UTC
477 // |is_local = false|.
478 void Explode(bool is_local
, Exploded
* exploded
) const;
480 // Unexplodes a given time assuming the source is either local time
481 // |is_local = true| or UTC |is_local = false|.
482 static Time
FromExploded(bool is_local
, const Exploded
& exploded
);
484 // Converts a string representation of time to a Time object.
485 // An example of a time string which is converted is as below:-
486 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
487 // in the input string, local time |is_local = true| or
488 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
489 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
490 // timezone is not specified.
491 static bool FromStringInternal(const char* time_string
,
495 // The representation of Jan 1, 1970 UTC in microseconds since the
496 // platform-dependent epoch.
497 static const int64 kTimeTToMicrosecondsOffset
;
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::FromSecondsD(double secs
) {
547 // Preserve max to prevent overflow.
548 if (secs
== std::numeric_limits
<double>::infinity())
550 return TimeDelta(static_cast<int64
>(secs
* Time::kMicrosecondsPerSecond
));
554 inline TimeDelta
TimeDelta::FromMillisecondsD(double ms
) {
555 // Preserve max to prevent overflow.
556 if (ms
== std::numeric_limits
<double>::infinity())
558 return TimeDelta(static_cast<int64
>(ms
* Time::kMicrosecondsPerMillisecond
));
562 inline TimeDelta
TimeDelta::FromMicroseconds(int64 us
) {
563 // Preserve max to prevent overflow.
564 if (us
== std::numeric_limits
<int64
>::max())
566 return TimeDelta(us
);
569 inline Time
TimeDelta::operator+(Time t
) const {
570 return Time(t
.us_
+ delta_
);
573 // For logging use only.
574 BASE_EXPORT
std::ostream
& operator<<(std::ostream
& os
, Time time
);
576 // TimeTicks ------------------------------------------------------------------
578 class BASE_EXPORT TimeTicks
{
580 // We define this even without OS_CHROMEOS for seccomp sandbox testing.
581 #if defined(OS_LINUX)
582 // Force definition of the system trace clock; it is a chromeos-only api
583 // at the moment and surfacing it in the right place requires mucking
585 static const clockid_t kClockSystemTrace
= 11;
588 TimeTicks() : ticks_(0) {
591 // Platform-dependent tick count representing "right now."
592 // The resolution of this clock is ~1-15ms. Resolution varies depending
593 // on hardware/operating system configuration.
594 static TimeTicks
Now();
596 // Returns a platform-dependent high-resolution tick count. Implementation
597 // is hardware dependent and may or may not return sub-millisecond
598 // resolution. THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND
599 // SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED.
600 static TimeTicks
HighResNow();
602 static bool IsHighResNowFastAndReliable();
604 // Returns true if ThreadNow() is supported on this system.
605 static bool IsThreadNowSupported() {
606 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
607 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
614 // Returns thread-specific CPU-time on systems that support this feature.
615 // Needs to be guarded with a call to IsThreadNowSupported(). Use this timer
616 // to (approximately) measure how much time the calling thread spent doing
617 // actual work vs. being de-scheduled. May return bogus results if the thread
618 // migrates to another CPU between two calls.
619 static TimeTicks
ThreadNow();
621 // Returns the current system trace time or, if none is defined, the current
622 // high-res time (i.e. HighResNow()). On systems where a global trace clock
623 // is defined, timestamping TraceEvents's with this value guarantees
624 // synchronization between events collected inside chrome and events
625 // collected outside (e.g. kernel, X server).
626 static TimeTicks
NowFromSystemTraceTime();
629 // Get the absolute value of QPC time drift. For testing.
630 static int64
GetQPCDriftMicroseconds();
632 static TimeTicks
FromQPCValue(LONGLONG qpc_value
);
634 // Returns true if the high resolution clock is working on this system.
635 // This is only for testing.
636 static bool IsHighResClockWorking();
638 // Returns a time value that is NOT rollover protected.
639 static TimeTicks
UnprotectedNow();
642 // Returns true if this object has not been initialized.
643 bool is_null() const {
647 // Converts an integer value representing TimeTicks to a class. This is used
648 // when deserializing a |TimeTicks| structure, using a value known to be
649 // compatible. It is not provided as a constructor because the integer type
650 // may be unclear from the perspective of a caller.
651 static TimeTicks
FromInternalValue(int64 ticks
) {
652 return TimeTicks(ticks
);
655 // Get the TimeTick value at the time of the UnixEpoch. This is useful when
656 // you need to relate the value of TimeTicks to a real time and date.
657 // Note: Upon first invocation, this function takes a snapshot of the realtime
658 // clock to establish a reference point. This function will return the same
659 // value for the duration of the application, but will be different in future
661 static TimeTicks
UnixEpoch();
663 // Returns the internal numeric value of the TimeTicks object.
664 // For serializing, use FromInternalValue to reconstitute.
665 int64
ToInternalValue() const {
669 TimeTicks
& operator=(TimeTicks other
) {
670 ticks_
= other
.ticks_
;
674 // Compute the difference between two times.
675 TimeDelta
operator-(TimeTicks other
) const {
676 return TimeDelta(ticks_
- other
.ticks_
);
679 // Modify by some time delta.
680 TimeTicks
& operator+=(TimeDelta delta
) {
681 ticks_
+= delta
.delta_
;
684 TimeTicks
& operator-=(TimeDelta delta
) {
685 ticks_
-= delta
.delta_
;
689 // Return a new TimeTicks modified by some delta.
690 TimeTicks
operator+(TimeDelta delta
) const {
691 return TimeTicks(ticks_
+ delta
.delta_
);
693 TimeTicks
operator-(TimeDelta delta
) const {
694 return TimeTicks(ticks_
- delta
.delta_
);
697 // Comparison operators
698 bool operator==(TimeTicks other
) const {
699 return ticks_
== other
.ticks_
;
701 bool operator!=(TimeTicks other
) const {
702 return ticks_
!= other
.ticks_
;
704 bool operator<(TimeTicks other
) const {
705 return ticks_
< other
.ticks_
;
707 bool operator<=(TimeTicks other
) const {
708 return ticks_
<= other
.ticks_
;
710 bool operator>(TimeTicks other
) const {
711 return ticks_
> other
.ticks_
;
713 bool operator>=(TimeTicks other
) const {
714 return ticks_
>= other
.ticks_
;
718 friend class TimeDelta
;
720 // Please use Now() to create a new object. This is for internal use
721 // and testing. Ticks is in microseconds.
722 explicit TimeTicks(int64 ticks
) : ticks_(ticks
) {
725 // Tick count in microseconds.
729 typedef DWORD (*TickFunctionType
)(void);
730 static TickFunctionType
SetMockTickFunction(TickFunctionType ticker
);
734 inline TimeTicks
TimeDelta::operator+(TimeTicks t
) const {
735 return TimeTicks(t
.ticks_
+ delta_
);
738 // For logging use only.
739 BASE_EXPORT
std::ostream
& operator<<(std::ostream
& os
, TimeTicks time_ticks
);
743 #endif // BASE_TIME_TIME_H_