1 // Copyright (c) 2011 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 a platform-dependent epoch. Each
7 // platform's epoch, along with other system-dependent clock interface
8 // routines, is defined in time_PLATFORM.cc.
10 // TimeDelta represents a duration of time, internally represented in
13 // TimeTicks represents an abstract time that is always incrementing for use
14 // in measuring time durations. It is internally represented in microseconds.
15 // It can not be converted to a human-readable time, but is guaranteed not to
16 // decrease (if the user changes the computer clock, Time::Now() may actually
19 // These classes are represented as only a 64-bit value, so they can be
20 // efficiently passed by value.
28 #include "base/atomicops.h"
29 #include "base/base_export.h"
30 #include "base/basictypes.h"
33 // For struct timeval.
38 // For FILETIME in FromFileTime, until it moves to a new converter class.
39 // See TODO(iyengar) below.
48 // TimeDelta ------------------------------------------------------------------
50 class BASE_EXPORT TimeDelta {
52 TimeDelta() : delta_(0) {
55 // Converts units of time to TimeDeltas.
56 static TimeDelta FromDays(int64 days);
57 static TimeDelta FromHours(int64 hours);
58 static TimeDelta FromMinutes(int64 minutes);
59 static TimeDelta FromSeconds(int64 secs);
60 static TimeDelta FromMilliseconds(int64 ms);
61 static TimeDelta FromMicroseconds(int64 us);
63 // Returns the internal numeric value of the TimeDelta object. Please don't
64 // use this and do arithmetic on it, as it is more error prone than using the
65 // provided operators.
66 int64 ToInternalValue() const {
71 struct timespec ToTimeSpec() const;
74 // Returns the time delta in some unit. The F versions return a floating
75 // point value, the "regular" versions return a rounded-down value.
77 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
78 // to the next full millisecond.
81 int InMinutes() const;
82 double InSecondsF() const;
83 int64 InSeconds() const;
84 double InMillisecondsF() const;
85 int64 InMilliseconds() const;
86 int64 InMillisecondsRoundedUp() const;
87 int64 InMicroseconds() const;
89 TimeDelta& operator=(TimeDelta other) {
90 delta_ = other.delta_;
94 // Computations with other deltas.
95 TimeDelta operator+(TimeDelta other) const {
96 return TimeDelta(delta_ + other.delta_);
98 TimeDelta operator-(TimeDelta other) const {
99 return TimeDelta(delta_ - other.delta_);
102 TimeDelta& operator+=(TimeDelta other) {
103 delta_ += other.delta_;
106 TimeDelta& operator-=(TimeDelta other) {
107 delta_ -= other.delta_;
110 TimeDelta operator-() const {
111 return TimeDelta(-delta_);
114 // Computations with ints, note that we only allow multiplicative operations
115 // with ints, and additive operations with other deltas.
116 TimeDelta operator*(int64 a) const {
117 return TimeDelta(delta_ * a);
119 TimeDelta operator/(int64 a) const {
120 return TimeDelta(delta_ / a);
122 TimeDelta& operator*=(int64 a) {
126 TimeDelta& operator/=(int64 a) {
130 int64 operator/(TimeDelta a) const {
131 return delta_ / a.delta_;
134 // Defined below because it depends on the definition of the other classes.
135 Time operator+(Time t) const;
136 TimeTicks operator+(TimeTicks t) const;
138 // Comparison operators.
139 bool operator==(TimeDelta other) const {
140 return delta_ == other.delta_;
142 bool operator!=(TimeDelta other) const {
143 return delta_ != other.delta_;
145 bool operator<(TimeDelta other) const {
146 return delta_ < other.delta_;
148 bool operator<=(TimeDelta other) const {
149 return delta_ <= other.delta_;
151 bool operator>(TimeDelta other) const {
152 return delta_ > other.delta_;
154 bool operator>=(TimeDelta other) const {
155 return delta_ >= other.delta_;
160 friend class TimeTicks;
161 friend TimeDelta operator*(int64 a, TimeDelta td);
163 // Constructs a delta given the duration in microseconds. This is private
164 // to avoid confusion by callers with an integer constructor. Use
165 // FromSeconds, FromMilliseconds, etc. instead.
166 explicit TimeDelta(int64 delta_us) : delta_(delta_us) {
169 // Delta in microseconds.
173 inline TimeDelta operator*(int64 a, TimeDelta td) {
174 return TimeDelta(a * td.delta_);
177 // Time -----------------------------------------------------------------------
179 // Represents a wall clock time.
180 class BASE_EXPORT Time {
182 static const int64 kMillisecondsPerSecond = 1000;
183 static const int64 kMicrosecondsPerMillisecond = 1000;
184 static const int64 kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
185 kMillisecondsPerSecond;
186 static const int64 kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
187 static const int64 kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
188 static const int64 kMicrosecondsPerDay = kMicrosecondsPerHour * 24;
189 static const int64 kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
190 static const int64 kNanosecondsPerMicrosecond = 1000;
191 static const int64 kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
192 kMicrosecondsPerSecond;
195 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
196 // the Posix delta of 1970. This is used for migrating between the old
197 // 1970-based epochs to the new 1601-based ones. It should be removed from
198 // this global header and put in the platform-specific ones when we remove the
200 static const int64 kWindowsEpochDeltaMicroseconds;
203 // Represents an exploded time that can be formatted nicely. This is kind of
204 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
205 // additions and changes to prevent errors.
206 struct BASE_EXPORT Exploded {
207 int year; // Four digit year "2007"
208 int month; // 1-based month (values 1 = January, etc.)
209 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
210 int day_of_month; // 1-based day of month (1-31)
211 int hour; // Hour within the current day (0-23)
212 int minute; // Minute within the current hour (0-59)
213 int second; // Second within the current minute (0-59 plus leap
214 // seconds which may take it up to 60).
215 int millisecond; // Milliseconds within the current second (0-999)
217 // A cursory test for whether the data members are within their
218 // respective ranges. A 'true' return value does not guarantee the
219 // Exploded value can be successfully converted to a Time value.
220 bool HasValidValues() const;
223 // Contains the NULL time. Use Time::Now() to get the current time.
224 explicit Time() : us_(0) {
227 // Returns true if the time object has not been initialized.
228 bool is_null() const {
232 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
233 static Time UnixEpoch();
235 // Returns the current time. Watch out, the system might adjust its clock
236 // in which case time will actually go backwards. We don't guarantee that
237 // times are increasing, or that two calls to Now() won't be the same.
240 // Returns the current time. Same as Now() except that this function always
241 // uses system time so that there are no discrepancies between the returned
242 // time and system time even on virtual environments including our test bot.
243 // For timing sensitive unittests, this function should be used.
244 static Time NowFromSystemTime();
246 // Converts to/from time_t in UTC and a Time class.
247 // TODO(brettw) this should be removed once everybody starts using the |Time|
249 static Time FromTimeT(time_t tt);
250 time_t ToTimeT() const;
252 // Converts time to/from a double which is the number of seconds since epoch
253 // (Jan 1, 1970). Webkit uses this format to represent time.
254 // Because WebKit initializes double time value to 0 to indicate "not
255 // initialized", we map it to empty Time object that also means "not
257 static Time FromDoubleT(double dt);
258 double ToDoubleT() const;
260 #if defined(OS_POSIX)
261 struct timeval ToTimeVal() const;
265 static Time FromFileTime(FILETIME ft);
266 FILETIME ToFileTime() const;
268 // The minimum time of a low resolution timer. This is basically a windows
269 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
270 // treat it as static across all windows versions.
271 static const int kMinLowResolutionThresholdMs = 16;
273 // Enable or disable Windows high resolution timer. If the high resolution
274 // timer is not enabled, calls to ActivateHighResolutionTimer will fail.
275 // When disabling the high resolution timer, this function will not cause
276 // the high resolution timer to be deactivated, but will prevent future
278 // Must be called from the main thread.
279 // For more details see comments in time_win.cc.
280 static void EnableHighResolutionTimer(bool enable);
282 // Activates or deactivates the high resolution timer based on the |activate|
283 // flag. If the HighResolutionTimer is not Enabled (see
284 // EnableHighResolutionTimer), this function will return false. Otherwise
285 // returns true. Each successful activate call must be paired with a
286 // subsequent deactivate call.
287 // All callers to activate the high resolution timer must eventually call
288 // this function to deactivate the high resolution timer.
289 static bool ActivateHighResolutionTimer(bool activate);
291 // Returns true if the high resolution timer is both enabled and activated.
292 // This is provided for testing only, and is not tracked in a thread-safe
294 static bool IsHighResolutionTimerInUse();
297 // Converts an exploded structure representing either the local time or UTC
298 // into a Time class.
299 static Time FromUTCExploded(const Exploded& exploded) {
300 return FromExploded(false, exploded);
302 static Time FromLocalExploded(const Exploded& exploded) {
303 return FromExploded(true, exploded);
306 // Converts an integer value representing Time to a class. This is used
307 // when deserializing a |Time| structure, using a value known to be
308 // compatible. It is not provided as a constructor because the integer type
309 // may be unclear from the perspective of a caller.
310 static Time FromInternalValue(int64 us) {
314 // Converts a string representation of time to a Time object.
315 // An example of a time string which is converted is as below:-
316 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
317 // in the input string, we assume local time.
318 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
319 // a new time converter class.
320 static bool FromString(const char* time_string, Time* parsed_time);
322 // For serializing, use FromInternalValue to reconstitute. Please don't use
323 // this and do arithmetic on it, as it is more error prone than using the
324 // provided operators.
325 int64 ToInternalValue() const {
329 // Fills the given exploded structure with either the local time or UTC from
330 // this time structure (containing UTC).
331 void UTCExplode(Exploded* exploded) const {
332 return Explode(false, exploded);
334 void LocalExplode(Exploded* exploded) const {
335 return Explode(true, exploded);
338 // Rounds this time down to the nearest day in local time. It will represent
339 // midnight on that day.
340 Time LocalMidnight() const;
342 Time& operator=(Time other) {
347 // Compute the difference between two times.
348 TimeDelta operator-(Time other) const {
349 return TimeDelta(us_ - other.us_);
352 // Modify by some time delta.
353 Time& operator+=(TimeDelta delta) {
357 Time& operator-=(TimeDelta delta) {
362 // Return a new time modified by some delta.
363 Time operator+(TimeDelta delta) const {
364 return Time(us_ + delta.delta_);
366 Time operator-(TimeDelta delta) const {
367 return Time(us_ - delta.delta_);
370 // Comparison operators
371 bool operator==(Time other) const {
372 return us_ == other.us_;
374 bool operator!=(Time other) const {
375 return us_ != other.us_;
377 bool operator<(Time other) const {
378 return us_ < other.us_;
380 bool operator<=(Time other) const {
381 return us_ <= other.us_;
383 bool operator>(Time other) const {
384 return us_ > other.us_;
386 bool operator>=(Time other) const {
387 return us_ >= other.us_;
391 friend class TimeDelta;
393 explicit Time(int64 us) : us_(us) {
396 // Explodes the given time to either local time |is_local = true| or UTC
397 // |is_local = false|.
398 void Explode(bool is_local, Exploded* exploded) const;
400 // Unexplodes a given time assuming the source is either local time
401 // |is_local = true| or UTC |is_local = false|.
402 static Time FromExploded(bool is_local, const Exploded& exploded);
404 // The representation of Jan 1, 1970 UTC in microseconds since the
405 // platform-dependent epoch.
406 static const int64 kTimeTToMicrosecondsOffset;
409 // Indicates whether fast timers are usable right now. For instance,
410 // when using battery power, we might elect to prevent high speed timers
411 // which would draw more power.
412 static bool high_resolution_timer_enabled_;
413 // Count of activations on the high resolution timer. Only use in tests
414 // which are single threaded.
415 static int high_resolution_timer_activated_;
418 // Time in microseconds in UTC.
422 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
425 inline TimeDelta TimeDelta::FromDays(int64 days) {
426 return TimeDelta(days * Time::kMicrosecondsPerDay);
430 inline TimeDelta TimeDelta::FromHours(int64 hours) {
431 return TimeDelta(hours * Time::kMicrosecondsPerHour);
435 inline TimeDelta TimeDelta::FromMinutes(int64 minutes) {
436 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
440 inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
441 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
445 inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
446 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
450 inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
451 return TimeDelta(us);
454 inline Time TimeDelta::operator+(Time t) const {
455 return Time(t.us_ + delta_);
458 // TimeTicks ------------------------------------------------------------------
460 class BASE_EXPORT TimeTicks {
462 TimeTicks() : ticks_(0) {
465 // Platform-dependent tick count representing "right now."
466 // The resolution of this clock is ~1-15ms. Resolution varies depending
467 // on hardware/operating system configuration.
468 static TimeTicks Now();
470 // Returns a platform-dependent high-resolution tick count. Implementation
471 // is hardware dependent and may or may not return sub-millisecond
472 // resolution. THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND
473 // SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED.
474 static TimeTicks HighResNow();
477 // Get the absolute value of QPC time drift. For testing.
478 static int64 GetQPCDriftMicroseconds();
480 // Returns true if the high resolution clock is working on this system.
481 // This is only for testing.
482 static bool IsHighResClockWorking();
485 // Returns true if this object has not been initialized.
486 bool is_null() const {
490 // Returns the internal numeric value of the TimeTicks object.
491 int64 ToInternalValue() const {
495 TimeTicks& operator=(TimeTicks other) {
496 ticks_ = other.ticks_;
500 // Compute the difference between two times.
501 TimeDelta operator-(TimeTicks other) const {
502 return TimeDelta(ticks_ - other.ticks_);
505 // Modify by some time delta.
506 TimeTicks& operator+=(TimeDelta delta) {
507 ticks_ += delta.delta_;
510 TimeTicks& operator-=(TimeDelta delta) {
511 ticks_ -= delta.delta_;
515 // Return a new TimeTicks modified by some delta.
516 TimeTicks operator+(TimeDelta delta) const {
517 return TimeTicks(ticks_ + delta.delta_);
519 TimeTicks operator-(TimeDelta delta) const {
520 return TimeTicks(ticks_ - delta.delta_);
523 // Comparison operators
524 bool operator==(TimeTicks other) const {
525 return ticks_ == other.ticks_;
527 bool operator!=(TimeTicks other) const {
528 return ticks_ != other.ticks_;
530 bool operator<(TimeTicks other) const {
531 return ticks_ < other.ticks_;
533 bool operator<=(TimeTicks other) const {
534 return ticks_ <= other.ticks_;
536 bool operator>(TimeTicks other) const {
537 return ticks_ > other.ticks_;
539 bool operator>=(TimeTicks other) const {
540 return ticks_ >= other.ticks_;
544 friend class TimeDelta;
546 // Please use Now() to create a new object. This is for internal use
547 // and testing. Ticks is in microseconds.
548 explicit TimeTicks(int64 ticks) : ticks_(ticks) {
551 // Tick count in microseconds.
555 typedef DWORD (*TickFunctionType)(void);
556 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
560 inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
561 return TimeTicks(t.ticks_ + delta_);
566 #endif // BASE_TIME_H_