DevTools: consistently use camel case for URL parameter names
[chromium-blink-merge.git] / base / time.h
blob1b05e24108232b53b587e4e2634cd62d5694e594
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.
9 //
10 // TimeDelta represents a duration of time, internally represented in
11 // microseconds.
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
17 // decrease or jump).
19 // These classes are represented as only a 64-bit value, so they can be
20 // efficiently passed by value.
22 #ifndef BASE_TIME_H_
23 #define BASE_TIME_H_
24 #pragma once
26 #include <time.h>
28 #include "base/atomicops.h"
29 #include "base/base_api.h"
30 #include "base/basictypes.h"
32 #if defined(OS_POSIX)
33 // For struct timeval.
34 #include <sys/time.h>
35 #endif
37 #if defined(OS_WIN)
38 // For FILETIME in FromFileTime, until it moves to a new converter class.
39 // See TODO(iyengar) below.
40 #include <windows.h>
41 #endif
43 namespace base {
45 class Time;
46 class TimeTicks;
48 // TimeDelta ------------------------------------------------------------------
50 class BASE_API TimeDelta {
51 public:
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 {
67 return delta_;
70 #if defined(OS_POSIX)
71 struct timespec ToTimeSpec() const;
72 #endif
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.
79 int InDays() const;
80 int InHours() const;
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_;
91 return *this;
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_;
104 return *this;
106 TimeDelta& operator-=(TimeDelta other) {
107 delta_ -= other.delta_;
108 return *this;
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) {
123 delta_ *= a;
124 return *this;
126 TimeDelta& operator/=(int64 a) {
127 delta_ /= a;
128 return *this;
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_;
158 private:
159 friend class Time;
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.
170 int64 delta_;
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_API Time {
181 public:
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;
194 #if !defined(OS_WIN)
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
199 // migration code.
200 static const int64 kWindowsEpochDeltaMicroseconds;
201 #endif
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_API 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 {
229 return us_ == 0;
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.
238 static Time Now();
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|
248 // class.
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
256 // initialized".
257 static Time FromDoubleT(double dt);
258 double ToDoubleT() const;
260 #if defined(OS_POSIX)
261 struct timeval ToTimeVal() const;
262 #endif
264 #if defined(OS_WIN)
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
277 // activations.
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
293 // way.
294 static bool IsHighResolutionTimerInUse();
295 #endif
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) {
311 return Time(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 wchar_t* 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 {
326 return us_;
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) {
343 us_ = other.us_;
344 return *this;
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) {
354 us_ += delta.delta_;
355 return *this;
357 Time& operator-=(TimeDelta delta) {
358 us_ -= delta.delta_;
359 return *this;
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_;
390 private:
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;
408 #if defined(OS_WIN)
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_;
416 #endif
418 // Time in microseconds in UTC.
419 int64 us_;
422 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
424 // static
425 inline TimeDelta TimeDelta::FromDays(int64 days) {
426 return TimeDelta(days * Time::kMicrosecondsPerDay);
429 // static
430 inline TimeDelta TimeDelta::FromHours(int64 hours) {
431 return TimeDelta(hours * Time::kMicrosecondsPerHour);
434 // static
435 inline TimeDelta TimeDelta::FromMinutes(int64 minutes) {
436 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
439 // static
440 inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
441 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
444 // static
445 inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
446 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
449 // static
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_API TimeTicks {
461 public:
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();
476 #if defined(OS_WIN)
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();
483 #endif
485 // Returns true if this object has not been initialized.
486 bool is_null() const {
487 return ticks_ == 0;
490 // Returns the internal numeric value of the TimeTicks object.
491 int64 ToInternalValue() const {
492 return ticks_;
495 TimeTicks& operator=(TimeTicks other) {
496 ticks_ = other.ticks_;
497 return *this;
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_;
508 return *this;
510 TimeTicks& operator-=(TimeDelta delta) {
511 ticks_ -= delta.delta_;
512 return *this;
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_;
543 protected:
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.
552 int64 ticks_;
554 #if defined(OS_WIN)
555 typedef DWORD (*TickFunctionType)(void);
556 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
557 #endif
560 inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
561 return TimeTicks(t.ticks_ + delta_);
564 } // namespace base
566 #endif // BASE_TIME_H_