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 #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
FromSecondsD(double secs
);
70 static TimeDelta
FromMillisecondsD(double ms
);
71 static TimeDelta
FromMicroseconds(int64 us
);
73 static TimeDelta
FromQPCValue(LONGLONG qpc_value
);
76 // Converts an integer value representing TimeDelta to a class. This is used
77 // when deserializing a |TimeDelta| structure, using a value known to be
78 // compatible. It is not provided as a constructor because the integer type
79 // may be unclear from the perspective of a caller.
80 static TimeDelta
FromInternalValue(int64 delta
) {
81 return TimeDelta(delta
);
84 // Returns the maximum time delta, which should be greater than any reasonable
85 // time delta we might compare it to. Adding or subtracting the maximum time
86 // delta to a time or another time delta has an undefined result.
87 static TimeDelta
Max();
89 // Returns the internal numeric value of the TimeDelta object. Please don't
90 // use this and do arithmetic on it, as it is more error prone than using the
91 // provided operators.
92 // For serializing, use FromInternalValue to reconstitute.
93 int64
ToInternalValue() const {
97 // Returns true if the time delta is the maximum time delta.
99 return delta_
== std::numeric_limits
<int64
>::max();
102 #if defined(OS_POSIX)
103 struct timespec
ToTimeSpec() const;
106 // Returns the time delta in some unit. The F versions return a floating
107 // point value, the "regular" versions return a rounded-down value.
109 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
110 // to the next full millisecond.
113 int InMinutes() const;
114 double InSecondsF() const;
115 int64
InSeconds() const;
116 double InMillisecondsF() const;
117 int64
InMilliseconds() const;
118 int64
InMillisecondsRoundedUp() const;
119 int64
InMicroseconds() const;
121 TimeDelta
& operator=(TimeDelta other
) {
122 delta_
= other
.delta_
;
126 // Computations with other deltas.
127 TimeDelta
operator+(TimeDelta other
) const {
128 return TimeDelta(delta_
+ other
.delta_
);
130 TimeDelta
operator-(TimeDelta other
) const {
131 return TimeDelta(delta_
- other
.delta_
);
134 TimeDelta
& operator+=(TimeDelta other
) {
135 delta_
+= other
.delta_
;
138 TimeDelta
& operator-=(TimeDelta other
) {
139 delta_
-= other
.delta_
;
142 TimeDelta
operator-() const {
143 return TimeDelta(-delta_
);
146 // Computations with ints, note that we only allow multiplicative operations
147 // with ints, and additive operations with other deltas.
148 TimeDelta
operator*(int64 a
) const {
149 return TimeDelta(delta_
* a
);
151 TimeDelta
operator/(int64 a
) const {
152 return TimeDelta(delta_
/ a
);
154 TimeDelta
& operator*=(int64 a
) {
158 TimeDelta
& operator/=(int64 a
) {
162 int64
operator/(TimeDelta a
) const {
163 return delta_
/ a
.delta_
;
166 // Defined below because it depends on the definition of the other classes.
167 Time
operator+(Time t
) const;
168 TimeTicks
operator+(TimeTicks t
) const;
170 // Comparison operators.
171 bool operator==(TimeDelta other
) const {
172 return delta_
== other
.delta_
;
174 bool operator!=(TimeDelta other
) const {
175 return delta_
!= other
.delta_
;
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_
;
192 friend class TimeTicks
;
193 friend TimeDelta
operator*(int64 a
, TimeDelta td
);
195 // Constructs a delta given the duration in microseconds. This is private
196 // to avoid confusion by callers with an integer constructor. Use
197 // FromSeconds, FromMilliseconds, etc. instead.
198 explicit TimeDelta(int64 delta_us
) : delta_(delta_us
) {
201 // Delta in microseconds.
205 inline TimeDelta
operator*(int64 a
, TimeDelta td
) {
206 return TimeDelta(a
* td
.delta_
);
209 // Time -----------------------------------------------------------------------
211 // Represents a wall clock time in UTC.
212 class BASE_EXPORT Time
{
214 static const int64 kMillisecondsPerSecond
= 1000;
215 static const int64 kMicrosecondsPerMillisecond
= 1000;
216 static const int64 kMicrosecondsPerSecond
= kMicrosecondsPerMillisecond
*
217 kMillisecondsPerSecond
;
218 static const int64 kMicrosecondsPerMinute
= kMicrosecondsPerSecond
* 60;
219 static const int64 kMicrosecondsPerHour
= kMicrosecondsPerMinute
* 60;
220 static const int64 kMicrosecondsPerDay
= kMicrosecondsPerHour
* 24;
221 static const int64 kMicrosecondsPerWeek
= kMicrosecondsPerDay
* 7;
222 static const int64 kNanosecondsPerMicrosecond
= 1000;
223 static const int64 kNanosecondsPerSecond
= kNanosecondsPerMicrosecond
*
224 kMicrosecondsPerSecond
;
227 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
228 // the Posix delta of 1970. This is used for migrating between the old
229 // 1970-based epochs to the new 1601-based ones. It should be removed from
230 // this global header and put in the platform-specific ones when we remove the
232 static const int64 kWindowsEpochDeltaMicroseconds
;
234 // To avoid overflow in QPC to Microseconds calculations, since we multiply
235 // by kMicrosecondsPerSecond, then the QPC value should not exceed
236 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
237 static const int64 kQPCOverflowThreshold
= 0x8637BD05AF7;
240 // Represents an exploded time that can be formatted nicely. This is kind of
241 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
242 // additions and changes to prevent errors.
243 struct BASE_EXPORT Exploded
{
244 int year
; // Four digit year "2007"
245 int month
; // 1-based month (values 1 = January, etc.)
246 int day_of_week
; // 0-based day of week (0 = Sunday, etc.)
247 int day_of_month
; // 1-based day of month (1-31)
248 int hour
; // Hour within the current day (0-23)
249 int minute
; // Minute within the current hour (0-59)
250 int second
; // Second within the current minute (0-59 plus leap
251 // seconds which may take it up to 60).
252 int millisecond
; // Milliseconds within the current second (0-999)
254 // A cursory test for whether the data members are within their
255 // respective ranges. A 'true' return value does not guarantee the
256 // Exploded value can be successfully converted to a Time value.
257 bool HasValidValues() const;
260 // Contains the NULL time. Use Time::Now() to get the current time.
264 // Returns true if the time object has not been initialized.
265 bool is_null() const {
269 // Returns true if the time object is the maximum time.
270 bool is_max() const {
271 return us_
== std::numeric_limits
<int64
>::max();
274 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
275 static Time
UnixEpoch();
277 // Returns the current time. Watch out, the system might adjust its clock
278 // in which case time will actually go backwards. We don't guarantee that
279 // times are increasing, or that two calls to Now() won't be the same.
282 // Returns the maximum time, which should be greater than any reasonable time
283 // with which we might compare it.
286 // Returns the current time. Same as Now() except that this function always
287 // uses system time so that there are no discrepancies between the returned
288 // time and system time even on virtual environments including our test bot.
289 // For timing sensitive unittests, this function should be used.
290 static Time
NowFromSystemTime();
292 // Converts to/from time_t in UTC and a Time class.
293 // TODO(brettw) this should be removed once everybody starts using the |Time|
295 static Time
FromTimeT(time_t tt
);
296 time_t ToTimeT() const;
298 // Converts time to/from a double which is the number of seconds since epoch
299 // (Jan 1, 1970). Webkit uses this format to represent time.
300 // Because WebKit initializes double time value to 0 to indicate "not
301 // initialized", we map it to empty Time object that also means "not
303 static Time
FromDoubleT(double dt
);
304 double ToDoubleT() const;
306 #if defined(OS_POSIX)
307 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
308 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
309 // having a 1 second resolution, which agrees with
310 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
311 static Time
FromTimeSpec(const timespec
& ts
);
314 // Converts to/from the Javascript convention for times, a number of
315 // milliseconds since the epoch:
316 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
317 static Time
FromJsTime(double ms_since_epoch
);
318 double ToJsTime() const;
320 // Converts to Java convention for times, a number of
321 // milliseconds since the epoch.
322 int64
ToJavaTime() const;
324 #if defined(OS_POSIX)
325 static Time
FromTimeVal(struct timeval t
);
326 struct timeval
ToTimeVal() const;
329 #if defined(OS_MACOSX)
330 static Time
FromCFAbsoluteTime(CFAbsoluteTime t
);
331 CFAbsoluteTime
ToCFAbsoluteTime() const;
335 static Time
FromFileTime(FILETIME ft
);
336 FILETIME
ToFileTime() const;
338 // The minimum time of a low resolution timer. This is basically a windows
339 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
340 // treat it as static across all windows versions.
341 static const int kMinLowResolutionThresholdMs
= 16;
343 // Enable or disable Windows high resolution timer.
344 static void EnableHighResolutionTimer(bool enable
);
346 // Activates or deactivates the high resolution timer based on the |activate|
347 // flag. If the HighResolutionTimer is not Enabled (see
348 // EnableHighResolutionTimer), this function will return false. Otherwise
349 // returns true. Each successful activate call must be paired with a
350 // subsequent deactivate call.
351 // All callers to activate the high resolution timer must eventually call
352 // this function to deactivate the high resolution timer.
353 static bool ActivateHighResolutionTimer(bool activate
);
355 // Returns true if the high resolution timer is both enabled and activated.
356 // This is provided for testing only, and is not tracked in a thread-safe
358 static bool IsHighResolutionTimerInUse();
361 // Converts an exploded structure representing either the local time or UTC
362 // into a Time class.
363 static Time
FromUTCExploded(const Exploded
& exploded
) {
364 return FromExploded(false, exploded
);
366 static Time
FromLocalExploded(const Exploded
& exploded
) {
367 return FromExploded(true, exploded
);
370 // Converts an integer value representing Time to a class. This is used
371 // when deserializing a |Time| structure, using a value known to be
372 // compatible. It is not provided as a constructor because the integer type
373 // may be unclear from the perspective of a caller.
374 static Time
FromInternalValue(int64 us
) {
378 // Converts a string representation of time to a Time object.
379 // An example of a time string which is converted is as below:-
380 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
381 // in the input string, FromString assumes local time and FromUTCString
382 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
383 // specified in RFC822) is treated as if the timezone is not specified.
384 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
385 // a new time converter class.
386 static bool FromString(const char* time_string
, Time
* parsed_time
) {
387 return FromStringInternal(time_string
, true, parsed_time
);
389 static bool FromUTCString(const char* time_string
, Time
* parsed_time
) {
390 return FromStringInternal(time_string
, false, parsed_time
);
393 // For serializing, use FromInternalValue to reconstitute. Please don't use
394 // this and do arithmetic on it, as it is more error prone than using the
395 // provided operators.
396 int64
ToInternalValue() const {
400 // Fills the given exploded structure with either the local time or UTC from
401 // this time structure (containing UTC).
402 void UTCExplode(Exploded
* exploded
) const {
403 return Explode(false, exploded
);
405 void LocalExplode(Exploded
* exploded
) const {
406 return Explode(true, exploded
);
409 // Rounds this time down to the nearest day in local time. It will represent
410 // midnight on that day.
411 Time
LocalMidnight() const;
413 Time
& operator=(Time other
) {
418 // Compute the difference between two times.
419 TimeDelta
operator-(Time other
) const {
420 return TimeDelta(us_
- other
.us_
);
423 // Modify by some time delta.
424 Time
& operator+=(TimeDelta delta
) {
428 Time
& operator-=(TimeDelta delta
) {
433 // Return a new time modified by some delta.
434 Time
operator+(TimeDelta delta
) const {
435 return Time(us_
+ delta
.delta_
);
437 Time
operator-(TimeDelta delta
) const {
438 return Time(us_
- delta
.delta_
);
441 // Comparison operators
442 bool operator==(Time other
) const {
443 return us_
== other
.us_
;
445 bool operator!=(Time other
) const {
446 return us_
!= other
.us_
;
448 bool operator<(Time other
) const {
449 return us_
< other
.us_
;
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_
;
462 friend class TimeDelta
;
464 explicit Time(int64 us
) : us_(us
) {
467 // Explodes the given time to either local time |is_local = true| or UTC
468 // |is_local = false|.
469 void Explode(bool is_local
, Exploded
* exploded
) const;
471 // Unexplodes a given time assuming the source is either local time
472 // |is_local = true| or UTC |is_local = false|.
473 static Time
FromExploded(bool is_local
, const Exploded
& exploded
);
475 // Converts a string representation of time to a Time object.
476 // An example of a time string which is converted is as below:-
477 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
478 // in the input string, local time |is_local = true| or
479 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
480 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
481 // timezone is not specified.
482 static bool FromStringInternal(const char* time_string
,
486 // The representation of Jan 1, 1970 UTC in microseconds since the
487 // platform-dependent epoch.
488 static const int64 kTimeTToMicrosecondsOffset
;
490 // Time in microseconds in UTC.
494 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
497 inline TimeDelta
TimeDelta::FromDays(int days
) {
498 // Preserve max to prevent overflow.
499 if (days
== std::numeric_limits
<int>::max())
501 return TimeDelta(days
* Time::kMicrosecondsPerDay
);
505 inline TimeDelta
TimeDelta::FromHours(int hours
) {
506 // Preserve max to prevent overflow.
507 if (hours
== std::numeric_limits
<int>::max())
509 return TimeDelta(hours
* Time::kMicrosecondsPerHour
);
513 inline TimeDelta
TimeDelta::FromMinutes(int minutes
) {
514 // Preserve max to prevent overflow.
515 if (minutes
== std::numeric_limits
<int>::max())
517 return TimeDelta(minutes
* Time::kMicrosecondsPerMinute
);
521 inline TimeDelta
TimeDelta::FromSeconds(int64 secs
) {
522 // Preserve max to prevent overflow.
523 if (secs
== std::numeric_limits
<int64
>::max())
525 return TimeDelta(secs
* Time::kMicrosecondsPerSecond
);
529 inline TimeDelta
TimeDelta::FromMilliseconds(int64 ms
) {
530 // Preserve max to prevent overflow.
531 if (ms
== std::numeric_limits
<int64
>::max())
533 return TimeDelta(ms
* Time::kMicrosecondsPerMillisecond
);
537 inline TimeDelta
TimeDelta::FromSecondsD(double secs
) {
538 // Preserve max to prevent overflow.
539 if (secs
== std::numeric_limits
<double>::infinity())
541 return TimeDelta(secs
* Time::kMicrosecondsPerSecond
);
545 inline TimeDelta
TimeDelta::FromMillisecondsD(double ms
) {
546 // Preserve max to prevent overflow.
547 if (ms
== std::numeric_limits
<double>::infinity())
549 return TimeDelta(ms
* Time::kMicrosecondsPerMillisecond
);
553 inline TimeDelta
TimeDelta::FromMicroseconds(int64 us
) {
554 // Preserve max to prevent overflow.
555 if (us
== std::numeric_limits
<int64
>::max())
557 return TimeDelta(us
);
560 inline Time
TimeDelta::operator+(Time t
) const {
561 return Time(t
.us_
+ delta_
);
564 // TimeTicks ------------------------------------------------------------------
566 class BASE_EXPORT TimeTicks
{
568 // We define this even without OS_CHROMEOS for seccomp sandbox testing.
569 #if defined(OS_LINUX)
570 // Force definition of the system trace clock; it is a chromeos-only api
571 // at the moment and surfacing it in the right place requires mucking
573 static const clockid_t kClockSystemTrace
= 11;
576 TimeTicks() : ticks_(0) {
579 // Platform-dependent tick count representing "right now."
580 // The resolution of this clock is ~1-15ms. Resolution varies depending
581 // on hardware/operating system configuration.
582 static TimeTicks
Now();
584 // Returns a platform-dependent high-resolution tick count. Implementation
585 // is hardware dependent and may or may not return sub-millisecond
586 // resolution. THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND
587 // SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED.
588 static TimeTicks
HighResNow();
590 static bool IsHighResNowFastAndReliable();
592 // Returns true if ThreadNow() is supported on this system.
593 static bool IsThreadNowSupported() {
594 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
595 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
602 // Returns thread-specific CPU-time on systems that support this feature.
603 // Needs to be guarded with a call to IsThreadNowSupported(). Use this timer
604 // to (approximately) measure how much time the calling thread spent doing
605 // actual work vs. being de-scheduled. May return bogus results if the thread
606 // migrates to another CPU between two calls.
607 static TimeTicks
ThreadNow();
609 // Returns the current system trace time or, if none is defined, the current
610 // high-res time (i.e. HighResNow()). On systems where a global trace clock
611 // is defined, timestamping TraceEvents's with this value guarantees
612 // synchronization between events collected inside chrome and events
613 // collected outside (e.g. kernel, X server).
614 static TimeTicks
NowFromSystemTraceTime();
617 // Get the absolute value of QPC time drift. For testing.
618 static int64
GetQPCDriftMicroseconds();
620 static TimeTicks
FromQPCValue(LONGLONG qpc_value
);
622 // Returns true if the high resolution clock is working on this system.
623 // This is only for testing.
624 static bool IsHighResClockWorking();
626 // Returns a time value that is NOT rollover protected.
627 static TimeTicks
UnprotectedNow();
630 // Returns true if this object has not been initialized.
631 bool is_null() const {
635 // Converts an integer value representing TimeTicks to a class. This is used
636 // when deserializing a |TimeTicks| structure, using a value known to be
637 // compatible. It is not provided as a constructor because the integer type
638 // may be unclear from the perspective of a caller.
639 static TimeTicks
FromInternalValue(int64 ticks
) {
640 return TimeTicks(ticks
);
643 // Get the TimeTick value at the time of the UnixEpoch. This is useful when
644 // you need to relate the value of TimeTicks to a real time and date.
645 // Note: Upon first invocation, this function takes a snapshot of the realtime
646 // clock to establish a reference point. This function will return the same
647 // value for the duration of the application, but will be different in future
649 static TimeTicks
UnixEpoch();
651 // Returns the internal numeric value of the TimeTicks object.
652 // For serializing, use FromInternalValue to reconstitute.
653 int64
ToInternalValue() const {
657 TimeTicks
& operator=(TimeTicks other
) {
658 ticks_
= other
.ticks_
;
662 // Compute the difference between two times.
663 TimeDelta
operator-(TimeTicks other
) const {
664 return TimeDelta(ticks_
- other
.ticks_
);
667 // Modify by some time delta.
668 TimeTicks
& operator+=(TimeDelta delta
) {
669 ticks_
+= delta
.delta_
;
672 TimeTicks
& operator-=(TimeDelta delta
) {
673 ticks_
-= delta
.delta_
;
677 // Return a new TimeTicks modified by some delta.
678 TimeTicks
operator+(TimeDelta delta
) const {
679 return TimeTicks(ticks_
+ delta
.delta_
);
681 TimeTicks
operator-(TimeDelta delta
) const {
682 return TimeTicks(ticks_
- delta
.delta_
);
685 // Comparison operators
686 bool operator==(TimeTicks other
) const {
687 return ticks_
== other
.ticks_
;
689 bool operator!=(TimeTicks other
) const {
690 return ticks_
!= other
.ticks_
;
692 bool operator<(TimeTicks other
) const {
693 return ticks_
< other
.ticks_
;
695 bool operator<=(TimeTicks other
) const {
696 return ticks_
<= other
.ticks_
;
698 bool operator>(TimeTicks other
) const {
699 return ticks_
> other
.ticks_
;
701 bool operator>=(TimeTicks other
) const {
702 return ticks_
>= other
.ticks_
;
706 friend class TimeDelta
;
708 // Please use Now() to create a new object. This is for internal use
709 // and testing. Ticks is in microseconds.
710 explicit TimeTicks(int64 ticks
) : ticks_(ticks
) {
713 // Tick count in microseconds.
717 typedef DWORD (*TickFunctionType
)(void);
718 static TickFunctionType
SetMockTickFunction(TickFunctionType ticker
);
722 inline TimeTicks
TimeDelta::operator+(TimeTicks t
) const {
723 return TimeTicks(t
.ticks_
+ delta_
);
728 #endif // BASE_TIME_TIME_H_