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(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 #if defined(OS_POSIX)
290 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
291 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
292 // having a 1 second resolution, which agrees with
293 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
294 static Time FromTimeSpec(const timespec& ts);
297 // Converts to/from the Javascript convention for times, a number of
298 // milliseconds since the epoch:
299 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
300 static Time FromJsTime(double ms_since_epoch);
301 double ToJsTime() const;
303 // Converts to Java convention for times, a number of
304 // milliseconds since the epoch.
305 int64 ToJavaTime() const;
307 #if defined(OS_POSIX)
308 static Time FromTimeVal(struct timeval t);
309 struct timeval ToTimeVal() const;
312 #if defined(OS_MACOSX)
313 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
314 CFAbsoluteTime ToCFAbsoluteTime() const;
318 static Time FromFileTime(FILETIME ft);
319 FILETIME ToFileTime() const;
321 // The minimum time of a low resolution timer. This is basically a windows
322 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
323 // treat it as static across all windows versions.
324 static const int kMinLowResolutionThresholdMs = 16;
326 // Enable or disable Windows high resolution timer. If the high resolution
327 // timer is not enabled, calls to ActivateHighResolutionTimer will fail.
328 // When disabling the high resolution timer, this function will not cause
329 // the high resolution timer to be deactivated, but will prevent future
331 // Must be called from the main thread.
332 // For more details see comments in time_win.cc.
333 static void EnableHighResolutionTimer(bool enable);
335 // Activates or deactivates the high resolution timer based on the |activate|
336 // flag. If the HighResolutionTimer is not Enabled (see
337 // EnableHighResolutionTimer), this function will return false. Otherwise
338 // returns true. Each successful activate call must be paired with a
339 // subsequent deactivate call.
340 // All callers to activate the high resolution timer must eventually call
341 // this function to deactivate the high resolution timer.
342 static bool ActivateHighResolutionTimer(bool activate);
344 // Returns true if the high resolution timer is both enabled and activated.
345 // This is provided for testing only, and is not tracked in a thread-safe
347 static bool IsHighResolutionTimerInUse();
350 // Converts an exploded structure representing either the local time or UTC
351 // into a Time class.
352 static Time FromUTCExploded(const Exploded& exploded) {
353 return FromExploded(false, exploded);
355 static Time FromLocalExploded(const Exploded& exploded) {
356 return FromExploded(true, exploded);
359 // Converts an integer value representing Time to a class. This is used
360 // when deserializing a |Time| structure, using a value known to be
361 // compatible. It is not provided as a constructor because the integer type
362 // may be unclear from the perspective of a caller.
363 static Time FromInternalValue(int64 us) {
367 // Converts a string representation of time to a Time object.
368 // An example of a time string which is converted is as below:-
369 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
370 // in the input string, FromString assumes local time and FromUTCString
371 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
372 // specified in RFC822) is treated as if the timezone is not specified.
373 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
374 // a new time converter class.
375 static bool FromString(const char* time_string, Time* parsed_time) {
376 return FromStringInternal(time_string, true, parsed_time);
378 static bool FromUTCString(const char* time_string, Time* parsed_time) {
379 return FromStringInternal(time_string, false, parsed_time);
382 // For serializing, use FromInternalValue to reconstitute. Please don't use
383 // this and do arithmetic on it, as it is more error prone than using the
384 // provided operators.
385 int64 ToInternalValue() const {
389 // Fills the given exploded structure with either the local time or UTC from
390 // this time structure (containing UTC).
391 void UTCExplode(Exploded* exploded) const {
392 return Explode(false, exploded);
394 void LocalExplode(Exploded* exploded) const {
395 return Explode(true, exploded);
398 // Rounds this time down to the nearest day in local time. It will represent
399 // midnight on that day.
400 Time LocalMidnight() const;
402 Time& operator=(Time other) {
407 // Compute the difference between two times.
408 TimeDelta operator-(Time other) const {
409 return TimeDelta(us_ - other.us_);
412 // Modify by some time delta.
413 Time& operator+=(TimeDelta delta) {
417 Time& operator-=(TimeDelta delta) {
422 // Return a new time modified by some delta.
423 Time operator+(TimeDelta delta) const {
424 return Time(us_ + delta.delta_);
426 Time operator-(TimeDelta delta) const {
427 return Time(us_ - delta.delta_);
430 // Comparison operators
431 bool operator==(Time other) const {
432 return us_ == other.us_;
434 bool operator!=(Time other) const {
435 return us_ != other.us_;
437 bool operator<(Time other) const {
438 return us_ < other.us_;
440 bool operator<=(Time other) const {
441 return us_ <= other.us_;
443 bool operator>(Time other) const {
444 return us_ > other.us_;
446 bool operator>=(Time other) const {
447 return us_ >= other.us_;
451 friend class TimeDelta;
453 explicit Time(int64 us) : us_(us) {
456 // Explodes the given time to either local time |is_local = true| or UTC
457 // |is_local = false|.
458 void Explode(bool is_local, Exploded* exploded) const;
460 // Unexplodes a given time assuming the source is either local time
461 // |is_local = true| or UTC |is_local = false|.
462 static Time FromExploded(bool is_local, const Exploded& exploded);
464 // Converts a string representation of time to a Time object.
465 // An example of a time string which is converted is as below:-
466 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
467 // in the input string, local time |is_local = true| or
468 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
469 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
470 // timezone is not specified.
471 static bool FromStringInternal(const char* time_string,
475 // The representation of Jan 1, 1970 UTC in microseconds since the
476 // platform-dependent epoch.
477 static const int64 kTimeTToMicrosecondsOffset;
480 // Indicates whether fast timers are usable right now. For instance,
481 // when using battery power, we might elect to prevent high speed timers
482 // which would draw more power.
483 static bool high_resolution_timer_enabled_;
484 // Count of activations on the high resolution timer. Only use in tests
485 // which are single threaded.
486 static int high_resolution_timer_activated_;
489 // Time in microseconds in UTC.
493 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
496 inline TimeDelta TimeDelta::FromDays(int64 days) {
497 return TimeDelta(days * Time::kMicrosecondsPerDay);
501 inline TimeDelta TimeDelta::FromHours(int64 hours) {
502 return TimeDelta(hours * Time::kMicrosecondsPerHour);
506 inline TimeDelta TimeDelta::FromMinutes(int64 minutes) {
507 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
511 inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
512 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
516 inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
517 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
521 inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
522 return TimeDelta(us);
525 inline Time TimeDelta::operator+(Time t) const {
526 return Time(t.us_ + delta_);
529 // TimeTicks ------------------------------------------------------------------
531 class BASE_EXPORT TimeTicks {
533 TimeTicks() : ticks_(0) {
536 // Platform-dependent tick count representing "right now."
537 // The resolution of this clock is ~1-15ms. Resolution varies depending
538 // on hardware/operating system configuration.
539 static TimeTicks Now();
541 // Returns a platform-dependent high-resolution tick count. Implementation
542 // is hardware dependent and may or may not return sub-millisecond
543 // resolution. THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND
544 // SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED.
545 static TimeTicks HighResNow();
547 static bool IsHighResNowFastAndReliable();
549 // Returns true if ThreadNow() is supported on this system.
550 static bool IsThreadNowSupported() {
551 #if defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)
558 // Returns thread-specific CPU-time on systems that support this feature.
559 // Needs to be guarded with a call to IsThreadNowSupported(). Use this timer
560 // to (approximately) measure how much time the calling thread spent doing
561 // actual work vs. being de-scheduled. May return bogus results if the thread
562 // migrates to another CPU between two calls.
563 static TimeTicks ThreadNow();
565 // Returns the current system trace time or, if none is defined, the current
566 // high-res time (i.e. HighResNow()). On systems where a global trace clock
567 // is defined, timestamping TraceEvents's with this value guarantees
568 // synchronization between events collected inside chrome and events
569 // collected outside (e.g. kernel, X server).
570 static TimeTicks NowFromSystemTraceTime();
573 // Get the absolute value of QPC time drift. For testing.
574 static int64 GetQPCDriftMicroseconds();
576 static TimeTicks FromQPCValue(LONGLONG qpc_value);
578 // Returns true if the high resolution clock is working on this system.
579 // This is only for testing.
580 static bool IsHighResClockWorking();
582 // Enable high resolution time for TimeTicks::Now(). This function will
583 // test for the availability of a working implementation of
584 // QueryPerformanceCounter(). If one is not available, this function does
585 // nothing and the resolution of Now() remains 1ms. Otherwise, all future
586 // calls to TimeTicks::Now() will have the higher resolution provided by QPC.
587 // Returns true if high resolution time was successfully enabled.
588 static bool SetNowIsHighResNowIfSupported();
590 // Returns a time value that is NOT rollover protected.
591 static TimeTicks UnprotectedNow();
594 // Returns true if this object has not been initialized.
595 bool is_null() const {
599 // Converts an integer value representing TimeTicks to a class. This is used
600 // when deserializing a |TimeTicks| structure, using a value known to be
601 // compatible. It is not provided as a constructor because the integer type
602 // may be unclear from the perspective of a caller.
603 static TimeTicks FromInternalValue(int64 ticks) {
604 return TimeTicks(ticks);
607 // Get the TimeTick value at the time of the UnixEpoch. This is useful when
608 // you need to relate the value of TimeTicks to a real time and date.
609 // Note: Upon first invocation, this function takes a snapshot of the realtime
610 // clock to establish a reference point. This function will return the same
611 // value for the duration of the application, but will be different in future
613 static TimeTicks UnixEpoch();
615 // Returns the internal numeric value of the TimeTicks object.
616 // For serializing, use FromInternalValue to reconstitute.
617 int64 ToInternalValue() const {
621 TimeTicks& operator=(TimeTicks other) {
622 ticks_ = other.ticks_;
626 // Compute the difference between two times.
627 TimeDelta operator-(TimeTicks other) const {
628 return TimeDelta(ticks_ - other.ticks_);
631 // Modify by some time delta.
632 TimeTicks& operator+=(TimeDelta delta) {
633 ticks_ += delta.delta_;
636 TimeTicks& operator-=(TimeDelta delta) {
637 ticks_ -= delta.delta_;
641 // Return a new TimeTicks modified by some delta.
642 TimeTicks operator+(TimeDelta delta) const {
643 return TimeTicks(ticks_ + delta.delta_);
645 TimeTicks operator-(TimeDelta delta) const {
646 return TimeTicks(ticks_ - delta.delta_);
649 // Comparison operators
650 bool operator==(TimeTicks other) const {
651 return ticks_ == other.ticks_;
653 bool operator!=(TimeTicks other) const {
654 return ticks_ != other.ticks_;
656 bool operator<(TimeTicks other) const {
657 return ticks_ < other.ticks_;
659 bool operator<=(TimeTicks other) const {
660 return ticks_ <= other.ticks_;
662 bool operator>(TimeTicks other) const {
663 return ticks_ > other.ticks_;
665 bool operator>=(TimeTicks other) const {
666 return ticks_ >= other.ticks_;
670 friend class TimeDelta;
672 // Please use Now() to create a new object. This is for internal use
673 // and testing. Ticks is in microseconds.
674 explicit TimeTicks(int64 ticks) : ticks_(ticks) {
677 // Tick count in microseconds.
681 typedef DWORD (*TickFunctionType)(void);
682 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
686 inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
687 return TimeTicks(t.ticks_ + delta_);
692 #endif // BASE_TIME_TIME_H_