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.
28 #include "base/atomicops.h"
29 #include "base/base_export.h"
30 #include "base/basictypes.h"
32 #if defined(OS_MACOSX)
33 #include <CoreFoundation/CoreFoundation.h>
34 // Avoid Mac system header macro leak.
39 // For struct timeval.
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(int64 days
);
65 static TimeDelta
FromHours(int64 hours
);
66 static TimeDelta
FromMinutes(int64 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 internal numeric value of the TimeDelta object. Please don't
83 // use this and do arithmetic on it, as it is more error prone than using the
84 // provided operators.
85 // For serializing, use FromInternalValue to reconstitute.
86 int64
ToInternalValue() const {
91 struct timespec
ToTimeSpec() const;
94 // Returns the time delta in some unit. The F versions return a floating
95 // point value, the "regular" versions return a rounded-down value.
97 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
98 // to the next full millisecond.
101 int InMinutes() const;
102 double InSecondsF() const;
103 int64
InSeconds() const;
104 double InMillisecondsF() const;
105 int64
InMilliseconds() const;
106 int64
InMillisecondsRoundedUp() const;
107 int64
InMicroseconds() const;
109 TimeDelta
& operator=(TimeDelta other
) {
110 delta_
= other
.delta_
;
114 // Computations with other deltas.
115 TimeDelta
operator+(TimeDelta other
) const {
116 return TimeDelta(delta_
+ other
.delta_
);
118 TimeDelta
operator-(TimeDelta other
) const {
119 return TimeDelta(delta_
- other
.delta_
);
122 TimeDelta
& operator+=(TimeDelta other
) {
123 delta_
+= other
.delta_
;
126 TimeDelta
& operator-=(TimeDelta other
) {
127 delta_
-= other
.delta_
;
130 TimeDelta
operator-() const {
131 return TimeDelta(-delta_
);
134 // Computations with ints, note that we only allow multiplicative operations
135 // with ints, and additive operations with other deltas.
136 TimeDelta
operator*(int64 a
) const {
137 return TimeDelta(delta_
* a
);
139 TimeDelta
operator/(int64 a
) const {
140 return TimeDelta(delta_
/ a
);
142 TimeDelta
& operator*=(int64 a
) {
146 TimeDelta
& operator/=(int64 a
) {
150 int64
operator/(TimeDelta a
) const {
151 return delta_
/ a
.delta_
;
154 // Defined below because it depends on the definition of the other classes.
155 Time
operator+(Time t
) const;
156 TimeTicks
operator+(TimeTicks t
) const;
158 // Comparison operators.
159 bool operator==(TimeDelta other
) const {
160 return delta_
== other
.delta_
;
162 bool operator!=(TimeDelta other
) const {
163 return delta_
!= other
.delta_
;
165 bool operator<(TimeDelta other
) const {
166 return delta_
< other
.delta_
;
168 bool operator<=(TimeDelta other
) const {
169 return delta_
<= other
.delta_
;
171 bool operator>(TimeDelta other
) const {
172 return delta_
> other
.delta_
;
174 bool operator>=(TimeDelta other
) const {
175 return delta_
>= other
.delta_
;
180 friend class TimeTicks
;
181 friend TimeDelta
operator*(int64 a
, TimeDelta td
);
183 // Constructs a delta given the duration in microseconds. This is private
184 // to avoid confusion by callers with an integer constructor. Use
185 // FromSeconds, FromMilliseconds, etc. instead.
186 explicit TimeDelta(int64 delta_us
) : delta_(delta_us
) {
189 // Delta in microseconds.
193 inline TimeDelta
operator*(int64 a
, TimeDelta td
) {
194 return TimeDelta(a
* td
.delta_
);
197 // Time -----------------------------------------------------------------------
199 // Represents a wall clock time.
200 class BASE_EXPORT Time
{
202 static const int64 kMillisecondsPerSecond
= 1000;
203 static const int64 kMicrosecondsPerMillisecond
= 1000;
204 static const int64 kMicrosecondsPerSecond
= kMicrosecondsPerMillisecond
*
205 kMillisecondsPerSecond
;
206 static const int64 kMicrosecondsPerMinute
= kMicrosecondsPerSecond
* 60;
207 static const int64 kMicrosecondsPerHour
= kMicrosecondsPerMinute
* 60;
208 static const int64 kMicrosecondsPerDay
= kMicrosecondsPerHour
* 24;
209 static const int64 kMicrosecondsPerWeek
= kMicrosecondsPerDay
* 7;
210 static const int64 kNanosecondsPerMicrosecond
= 1000;
211 static const int64 kNanosecondsPerSecond
= kNanosecondsPerMicrosecond
*
212 kMicrosecondsPerSecond
;
215 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
216 // the Posix delta of 1970. This is used for migrating between the old
217 // 1970-based epochs to the new 1601-based ones. It should be removed from
218 // this global header and put in the platform-specific ones when we remove the
220 static const int64 kWindowsEpochDeltaMicroseconds
;
223 // Represents an exploded time that can be formatted nicely. This is kind of
224 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
225 // additions and changes to prevent errors.
226 struct BASE_EXPORT Exploded
{
227 int year
; // Four digit year "2007"
228 int month
; // 1-based month (values 1 = January, etc.)
229 int day_of_week
; // 0-based day of week (0 = Sunday, etc.)
230 int day_of_month
; // 1-based day of month (1-31)
231 int hour
; // Hour within the current day (0-23)
232 int minute
; // Minute within the current hour (0-59)
233 int second
; // Second within the current minute (0-59 plus leap
234 // seconds which may take it up to 60).
235 int millisecond
; // Milliseconds within the current second (0-999)
237 // A cursory test for whether the data members are within their
238 // respective ranges. A 'true' return value does not guarantee the
239 // Exploded value can be successfully converted to a Time value.
240 bool HasValidValues() const;
243 // Contains the NULL time. Use Time::Now() to get the current time.
247 // Returns true if the time object has not been initialized.
248 bool is_null() const {
252 // Returns true if the time object is the maximum time.
253 bool is_max() const {
254 return us_
== std::numeric_limits
<int64
>::max();
257 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
258 static Time
UnixEpoch();
260 // Returns the current time. Watch out, the system might adjust its clock
261 // in which case time will actually go backwards. We don't guarantee that
262 // times are increasing, or that two calls to Now() won't be the same.
265 // Returns the maximum time, which should be greater than any reasonable time
266 // with which we might compare it.
269 // Returns the current time. Same as Now() except that this function always
270 // uses system time so that there are no discrepancies between the returned
271 // time and system time even on virtual environments including our test bot.
272 // For timing sensitive unittests, this function should be used.
273 static Time
NowFromSystemTime();
275 // Converts to/from time_t in UTC and a Time class.
276 // TODO(brettw) this should be removed once everybody starts using the |Time|
278 static Time
FromTimeT(time_t tt
);
279 time_t ToTimeT() const;
281 // Converts time to/from a double which is the number of seconds since epoch
282 // (Jan 1, 1970). Webkit uses this format to represent time.
283 // Because WebKit initializes double time value to 0 to indicate "not
284 // initialized", we map it to empty Time object that also means "not
286 static Time
FromDoubleT(double dt
);
287 double ToDoubleT() const;
289 // Converts to/from the Javascript convention for times, a number of
290 // milliseconds since the epoch:
291 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
292 static Time
FromJsTime(double ms_since_epoch
);
293 double ToJsTime() const;
295 #if defined(OS_POSIX)
296 static Time
FromTimeVal(struct timeval t
);
297 struct timeval
ToTimeVal() const;
300 #if defined(OS_MACOSX)
301 static Time
FromCFAbsoluteTime(CFAbsoluteTime t
);
302 CFAbsoluteTime
ToCFAbsoluteTime() const;
306 static Time
FromFileTime(FILETIME ft
);
307 FILETIME
ToFileTime() const;
309 // The minimum time of a low resolution timer. This is basically a windows
310 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
311 // treat it as static across all windows versions.
312 static const int kMinLowResolutionThresholdMs
= 16;
314 // Enable or disable Windows high resolution timer. If the high resolution
315 // timer is not enabled, calls to ActivateHighResolutionTimer will fail.
316 // When disabling the high resolution timer, this function will not cause
317 // the high resolution timer to be deactivated, but will prevent future
319 // Must be called from the main thread.
320 // For more details see comments in time_win.cc.
321 static void EnableHighResolutionTimer(bool enable
);
323 // Activates or deactivates the high resolution timer based on the |activate|
324 // flag. If the HighResolutionTimer is not Enabled (see
325 // EnableHighResolutionTimer), this function will return false. Otherwise
326 // returns true. Each successful activate call must be paired with a
327 // subsequent deactivate call.
328 // All callers to activate the high resolution timer must eventually call
329 // this function to deactivate the high resolution timer.
330 static bool ActivateHighResolutionTimer(bool activate
);
332 // Returns true if the high resolution timer is both enabled and activated.
333 // This is provided for testing only, and is not tracked in a thread-safe
335 static bool IsHighResolutionTimerInUse();
338 // Converts an exploded structure representing either the local time or UTC
339 // into a Time class.
340 static Time
FromUTCExploded(const Exploded
& exploded
) {
341 return FromExploded(false, exploded
);
343 static Time
FromLocalExploded(const Exploded
& exploded
) {
344 return FromExploded(true, exploded
);
347 // Converts an integer value representing Time to a class. This is used
348 // when deserializing a |Time| structure, using a value known to be
349 // compatible. It is not provided as a constructor because the integer type
350 // may be unclear from the perspective of a caller.
351 static Time
FromInternalValue(int64 us
) {
355 // Converts a string representation of time to a Time object.
356 // An example of a time string which is converted is as below:-
357 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
358 // in the input string, FromString assumes local time and FromUTCString
359 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
360 // specified in RFC822) is treated as if the timezone is not specified.
361 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
362 // a new time converter class.
363 static bool FromString(const char* time_string
, Time
* parsed_time
) {
364 return FromStringInternal(time_string
, true, parsed_time
);
366 static bool FromUTCString(const char* time_string
, Time
* parsed_time
) {
367 return FromStringInternal(time_string
, false, parsed_time
);
370 // For serializing, use FromInternalValue to reconstitute. Please don't use
371 // this and do arithmetic on it, as it is more error prone than using the
372 // provided operators.
373 int64
ToInternalValue() const {
377 // Fills the given exploded structure with either the local time or UTC from
378 // this time structure (containing UTC).
379 void UTCExplode(Exploded
* exploded
) const {
380 return Explode(false, exploded
);
382 void LocalExplode(Exploded
* exploded
) const {
383 return Explode(true, exploded
);
386 // Rounds this time down to the nearest day in local time. It will represent
387 // midnight on that day.
388 Time
LocalMidnight() const;
390 Time
& operator=(Time other
) {
395 // Compute the difference between two times.
396 TimeDelta
operator-(Time other
) const {
397 return TimeDelta(us_
- other
.us_
);
400 // Modify by some time delta.
401 Time
& operator+=(TimeDelta delta
) {
405 Time
& operator-=(TimeDelta delta
) {
410 // Return a new time modified by some delta.
411 Time
operator+(TimeDelta delta
) const {
412 return Time(us_
+ delta
.delta_
);
414 Time
operator-(TimeDelta delta
) const {
415 return Time(us_
- delta
.delta_
);
418 // Comparison operators
419 bool operator==(Time other
) const {
420 return us_
== other
.us_
;
422 bool operator!=(Time other
) const {
423 return us_
!= other
.us_
;
425 bool operator<(Time other
) const {
426 return us_
< other
.us_
;
428 bool operator<=(Time other
) const {
429 return us_
<= other
.us_
;
431 bool operator>(Time other
) const {
432 return us_
> other
.us_
;
434 bool operator>=(Time other
) const {
435 return us_
>= other
.us_
;
439 friend class TimeDelta
;
441 explicit Time(int64 us
) : us_(us
) {
444 // Explodes the given time to either local time |is_local = true| or UTC
445 // |is_local = false|.
446 void Explode(bool is_local
, Exploded
* exploded
) const;
448 // Unexplodes a given time assuming the source is either local time
449 // |is_local = true| or UTC |is_local = false|.
450 static Time
FromExploded(bool is_local
, const Exploded
& exploded
);
452 // Converts a string representation of time to a Time object.
453 // An example of a time string which is converted is as below:-
454 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
455 // in the input string, local time |is_local = true| or
456 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
457 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
458 // timezone is not specified.
459 static bool FromStringInternal(const char* time_string
,
463 // The representation of Jan 1, 1970 UTC in microseconds since the
464 // platform-dependent epoch.
465 static const int64 kTimeTToMicrosecondsOffset
;
468 // Indicates whether fast timers are usable right now. For instance,
469 // when using battery power, we might elect to prevent high speed timers
470 // which would draw more power.
471 static bool high_resolution_timer_enabled_
;
472 // Count of activations on the high resolution timer. Only use in tests
473 // which are single threaded.
474 static int high_resolution_timer_activated_
;
477 // Time in microseconds in UTC.
481 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
484 inline TimeDelta
TimeDelta::FromDays(int64 days
) {
485 return TimeDelta(days
* Time::kMicrosecondsPerDay
);
489 inline TimeDelta
TimeDelta::FromHours(int64 hours
) {
490 return TimeDelta(hours
* Time::kMicrosecondsPerHour
);
494 inline TimeDelta
TimeDelta::FromMinutes(int64 minutes
) {
495 return TimeDelta(minutes
* Time::kMicrosecondsPerMinute
);
499 inline TimeDelta
TimeDelta::FromSeconds(int64 secs
) {
500 return TimeDelta(secs
* Time::kMicrosecondsPerSecond
);
504 inline TimeDelta
TimeDelta::FromMilliseconds(int64 ms
) {
505 return TimeDelta(ms
* Time::kMicrosecondsPerMillisecond
);
509 inline TimeDelta
TimeDelta::FromMicroseconds(int64 us
) {
510 return TimeDelta(us
);
513 inline Time
TimeDelta::operator+(Time t
) const {
514 return Time(t
.us_
+ delta_
);
517 // TimeTicks ------------------------------------------------------------------
519 class BASE_EXPORT TimeTicks
{
521 TimeTicks() : ticks_(0) {
524 // Platform-dependent tick count representing "right now."
525 // The resolution of this clock is ~1-15ms. Resolution varies depending
526 // on hardware/operating system configuration.
527 static TimeTicks
Now();
529 // Returns a platform-dependent high-resolution tick count. Implementation
530 // is hardware dependent and may or may not return sub-millisecond
531 // resolution. THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND
532 // SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED.
533 static TimeTicks
HighResNow();
535 // Returns the current system trace time or, if none is defined, the current
536 // high-res time (i.e. HighResNow()). On systems where a global trace clock
537 // is defined, timestamping TraceEvents's with this value guarantees
538 // synchronization between events collected inside chrome and events
539 // collected outside (e.g. kernel, X server).
540 static TimeTicks
NowFromSystemTraceTime();
543 // Get the absolute value of QPC time drift. For testing.
544 static int64
GetQPCDriftMicroseconds();
546 static TimeTicks
FromQPCValue(LONGLONG qpc_value
);
548 // Returns true if the high resolution clock is working on this system.
549 // This is only for testing.
550 static bool IsHighResClockWorking();
553 // Returns true if this object has not been initialized.
554 bool is_null() const {
558 // Converts an integer value representing TimeTicks to a class. This is used
559 // when deserializing a |TimeTicks| structure, using a value known to be
560 // compatible. It is not provided as a constructor because the integer type
561 // may be unclear from the perspective of a caller.
562 static TimeTicks
FromInternalValue(int64 ticks
) {
563 return TimeTicks(ticks
);
566 // Returns the internal numeric value of the TimeTicks object.
567 // For serializing, use FromInternalValue to reconstitute.
568 int64
ToInternalValue() const {
572 TimeTicks
& operator=(TimeTicks other
) {
573 ticks_
= other
.ticks_
;
577 // Compute the difference between two times.
578 TimeDelta
operator-(TimeTicks other
) const {
579 return TimeDelta(ticks_
- other
.ticks_
);
582 // Modify by some time delta.
583 TimeTicks
& operator+=(TimeDelta delta
) {
584 ticks_
+= delta
.delta_
;
587 TimeTicks
& operator-=(TimeDelta delta
) {
588 ticks_
-= delta
.delta_
;
592 // Return a new TimeTicks modified by some delta.
593 TimeTicks
operator+(TimeDelta delta
) const {
594 return TimeTicks(ticks_
+ delta
.delta_
);
596 TimeTicks
operator-(TimeDelta delta
) const {
597 return TimeTicks(ticks_
- delta
.delta_
);
600 // Comparison operators
601 bool operator==(TimeTicks other
) const {
602 return ticks_
== other
.ticks_
;
604 bool operator!=(TimeTicks other
) const {
605 return ticks_
!= other
.ticks_
;
607 bool operator<(TimeTicks other
) const {
608 return ticks_
< other
.ticks_
;
610 bool operator<=(TimeTicks other
) const {
611 return ticks_
<= other
.ticks_
;
613 bool operator>(TimeTicks other
) const {
614 return ticks_
> other
.ticks_
;
616 bool operator>=(TimeTicks other
) const {
617 return ticks_
>= other
.ticks_
;
621 friend class TimeDelta
;
623 // Please use Now() to create a new object. This is for internal use
624 // and testing. Ticks is in microseconds.
625 explicit TimeTicks(int64 ticks
) : ticks_(ticks
) {
628 // Tick count in microseconds.
632 typedef DWORD (*TickFunctionType
)(void);
633 static TickFunctionType
SetMockTickFunction(TickFunctionType ticker
);
637 inline TimeTicks
TimeDelta::operator+(TimeTicks t
) const {
638 return TimeTicks(t
.ticks_
+ delta_
);
643 #endif // BASE_TIME_H_