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.
4
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.
12 //
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).
18 //
19 // These classes are represented as only a 64-bit value, so they can be
20 // efficiently passed by value.
21
22 #ifndef BASE_TIME_H_
23 #define BASE_TIME_H_
24 #pragma once
25
26 #include <time.h>
27
28 #include "base/base_api.h"
29 #include "base/basictypes.h"
30
31 #if defined(OS_POSIX)
32 // For struct timeval.
33 #include <sys/time.h>
34 #endif
35
36 #if defined(OS_WIN)
37 // For FILETIME in FromFileTime, until it moves to a new converter class.
38 // See TODO(iyengar) below.
39 #include <windows.h>
40 #endif
41
42 namespace base {
43
44 class Time;
45 class TimeTicks;
46
47 // This unit test does a lot of manual time manipulation.
48 class PageLoadTrackerUnitTest;
49
50 // TimeDelta ------------------------------------------------------------------
51
52 class BASE_API TimeDelta {
53 public:
TimeDelta()54 TimeDelta() : delta_(0) {
55 }
56
57 // Converts units of time to TimeDeltas.
58 static TimeDelta FromDays(int64 days);
59 static TimeDelta FromHours(int64 hours);
60 static TimeDelta FromMinutes(int64 minutes);
61 static TimeDelta FromSeconds(int64 secs);
62 static TimeDelta FromMilliseconds(int64 ms);
63 static TimeDelta FromMicroseconds(int64 us);
64
65 // Returns the internal numeric value of the TimeDelta object. Please don't
66 // use this and do arithmetic on it, as it is more error prone than using the
67 // provided operators.
ToInternalValue()68 int64 ToInternalValue() const {
69 return delta_;
70 }
71
72 #if defined(OS_POSIX)
73 struct timespec ToTimeSpec() const;
74 #endif
75
76 // Returns the time delta in some unit. The F versions return a floating
77 // point value, the "regular" versions return a rounded-down value.
78 //
79 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
80 // to the next full millisecond.
81 int InDays() const;
82 int InHours() const;
83 int InMinutes() const;
84 double InSecondsF() const;
85 int64 InSeconds() const;
86 double InMillisecondsF() const;
87 int64 InMilliseconds() const;
88 int64 InMillisecondsRoundedUp() const;
89 int64 InMicroseconds() const;
90
91 TimeDelta& operator=(TimeDelta other) {
92 delta_ = other.delta_;
93 return *this;
94 }
95
96 // Computations with other deltas.
97 TimeDelta operator+(TimeDelta other) const {
98 return TimeDelta(delta_ + other.delta_);
99 }
100 TimeDelta operator-(TimeDelta other) const {
101 return TimeDelta(delta_ - other.delta_);
102 }
103
104 TimeDelta& operator+=(TimeDelta other) {
105 delta_ += other.delta_;
106 return *this;
107 }
108 TimeDelta& operator-=(TimeDelta other) {
109 delta_ -= other.delta_;
110 return *this;
111 }
112 TimeDelta operator-() const {
113 return TimeDelta(-delta_);
114 }
115
116 // Computations with ints, note that we only allow multiplicative operations
117 // with ints, and additive operations with other deltas.
118 TimeDelta operator*(int64 a) const {
119 return TimeDelta(delta_ * a);
120 }
121 TimeDelta operator/(int64 a) const {
122 return TimeDelta(delta_ / a);
123 }
124 TimeDelta& operator*=(int64 a) {
125 delta_ *= a;
126 return *this;
127 }
128 TimeDelta& operator/=(int64 a) {
129 delta_ /= a;
130 return *this;
131 }
132 int64 operator/(TimeDelta a) const {
133 return delta_ / a.delta_;
134 }
135
136 // Defined below because it depends on the definition of the other classes.
137 Time operator+(Time t) const;
138 TimeTicks operator+(TimeTicks t) const;
139
140 // Comparison operators.
141 bool operator==(TimeDelta other) const {
142 return delta_ == other.delta_;
143 }
144 bool operator!=(TimeDelta other) const {
145 return delta_ != other.delta_;
146 }
147 bool operator<(TimeDelta other) const {
148 return delta_ < other.delta_;
149 }
150 bool operator<=(TimeDelta other) const {
151 return delta_ <= other.delta_;
152 }
153 bool operator>(TimeDelta other) const {
154 return delta_ > other.delta_;
155 }
156 bool operator>=(TimeDelta other) const {
157 return delta_ >= other.delta_;
158 }
159
160 private:
161 friend class Time;
162 friend class TimeTicks;
163 friend TimeDelta operator*(int64 a, TimeDelta td);
164
165 // Constructs a delta given the duration in microseconds. This is private
166 // to avoid confusion by callers with an integer constructor. Use
167 // FromSeconds, FromMilliseconds, etc. instead.
TimeDelta(int64 delta_us)168 explicit TimeDelta(int64 delta_us) : delta_(delta_us) {
169 }
170
171 // Delta in microseconds.
172 int64 delta_;
173 };
174
175 inline TimeDelta operator*(int64 a, TimeDelta td) {
176 return TimeDelta(a * td.delta_);
177 }
178
179 // Time -----------------------------------------------------------------------
180
181 // Represents a wall clock time.
182 class BASE_API Time {
183 public:
184 static const int64 kMillisecondsPerSecond = 1000;
185 static const int64 kMicrosecondsPerMillisecond = 1000;
186 static const int64 kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
187 kMillisecondsPerSecond;
188 static const int64 kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
189 static const int64 kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
190 static const int64 kMicrosecondsPerDay = kMicrosecondsPerHour * 24;
191 static const int64 kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
192 static const int64 kNanosecondsPerMicrosecond = 1000;
193 static const int64 kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
194 kMicrosecondsPerSecond;
195
196 #if !defined(OS_WIN)
197 // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
198 // the Posix delta of 1970. This is used for migrating between the old
199 // 1970-based epochs to the new 1601-based ones. It should be removed from
200 // this global header and put in the platform-specific ones when we remove the
201 // migration code.
202 static const int64 kWindowsEpochDeltaMicroseconds;
203 #endif
204
205 // Represents an exploded time that can be formatted nicely. This is kind of
206 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
207 // additions and changes to prevent errors.
208 struct BASE_API Exploded {
209 int year; // Four digit year "2007"
210 int month; // 1-based month (values 1 = January, etc.)
211 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
212 int day_of_month; // 1-based day of month (1-31)
213 int hour; // Hour within the current day (0-23)
214 int minute; // Minute within the current hour (0-59)
215 int second; // Second within the current minute (0-59 plus leap
216 // seconds which may take it up to 60).
217 int millisecond; // Milliseconds within the current second (0-999)
218
219 // A cursory test for whether the data members are within their
220 // respective ranges. A 'true' return value does not guarantee the
221 // Exploded value can be successfully converted to a Time value.
222 bool HasValidValues() const;
223 };
224
225 // Contains the NULL time. Use Time::Now() to get the current time.
Time()226 explicit Time() : us_(0) {
227 }
228
229 // Returns true if the time object has not been initialized.
is_null()230 bool is_null() const {
231 return us_ == 0;
232 }
233
234 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
235 static Time UnixEpoch();
236
237 // Returns the current time. Watch out, the system might adjust its clock
238 // in which case time will actually go backwards. We don't guarantee that
239 // times are increasing, or that two calls to Now() won't be the same.
240 static Time Now();
241
242 // Returns the current time. Same as Now() except that this function always
243 // uses system time so that there are no discrepancies between the returned
244 // time and system time even on virtual environments including our test bot.
245 // For timing sensitive unittests, this function should be used.
246 static Time NowFromSystemTime();
247
248 // Converts to/from time_t in UTC and a Time class.
249 // TODO(brettw) this should be removed once everybody starts using the |Time|
250 // class.
251 static Time FromTimeT(time_t tt);
252 time_t ToTimeT() const;
253
254 // Converts time to/from a double which is the number of seconds since epoch
255 // (Jan 1, 1970). Webkit uses this format to represent time.
256 // Because WebKit initializes double time value to 0 to indicate "not
257 // initialized", we map it to empty Time object that also means "not
258 // initialized".
259 static Time FromDoubleT(double dt);
260 double ToDoubleT() const;
261
262 #if defined(OS_POSIX)
263 struct timeval ToTimeVal() const;
264 #endif
265
266 #if defined(OS_WIN)
267 static Time FromFileTime(FILETIME ft);
268 FILETIME ToFileTime() const;
269
270 // The minimum time of a low resolution timer. This is basically a windows
271 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
272 // treat it as static across all windows versions.
273 static const int kMinLowResolutionThresholdMs = 16;
274
275 // Enable or disable Windows high resolution timer. If the high resolution
276 // timer is not enabled, calls to ActivateHighResolutionTimer will fail.
277 // When disabling the high resolution timer, this function will not cause
278 // the high resolution timer to be deactivated, but will prevent future
279 // activations.
280 // Must be called from the main thread.
281 // For more details see comments in time_win.cc.
282 static void EnableHighResolutionTimer(bool enable);
283
284 // Activates or deactivates the high resolution timer based on the |activate|
285 // flag. If the HighResolutionTimer is not Enabled (see
286 // EnableHighResolutionTimer), this function will return false. Otherwise
287 // returns true.
288 // All callers to activate the high resolution timer must eventually call
289 // this function to deactivate the high resolution timer.
290 static bool ActivateHighResolutionTimer(bool activate);
291 #endif
292
293 // Converts an exploded structure representing either the local time or UTC
294 // into a Time class.
FromUTCExploded(const Exploded & exploded)295 static Time FromUTCExploded(const Exploded& exploded) {
296 return FromExploded(false, exploded);
297 }
FromLocalExploded(const Exploded & exploded)298 static Time FromLocalExploded(const Exploded& exploded) {
299 return FromExploded(true, exploded);
300 }
301
302 // Converts an integer value representing Time to a class. This is used
303 // when deserializing a |Time| structure, using a value known to be
304 // compatible. It is not provided as a constructor because the integer type
305 // may be unclear from the perspective of a caller.
FromInternalValue(int64 us)306 static Time FromInternalValue(int64 us) {
307 return Time(us);
308 }
309
310 // Converts a string representation of time to a Time object.
311 // An example of a time string which is converted is as below:-
312 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
313 // in the input string, we assume local time.
314 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
315 // a new time converter class.
316 static bool FromString(const wchar_t* time_string, Time* parsed_time);
317
318 // For serializing, use FromInternalValue to reconstitute. Please don't use
319 // this and do arithmetic on it, as it is more error prone than using the
320 // provided operators.
ToInternalValue()321 int64 ToInternalValue() const {
322 return us_;
323 }
324
325 // Fills the given exploded structure with either the local time or UTC from
326 // this time structure (containing UTC).
UTCExplode(Exploded * exploded)327 void UTCExplode(Exploded* exploded) const {
328 return Explode(false, exploded);
329 }
LocalExplode(Exploded * exploded)330 void LocalExplode(Exploded* exploded) const {
331 return Explode(true, exploded);
332 }
333
334 // Rounds this time down to the nearest day in local time. It will represent
335 // midnight on that day.
336 Time LocalMidnight() const;
337
338 Time& operator=(Time other) {
339 us_ = other.us_;
340 return *this;
341 }
342
343 // Compute the difference between two times.
344 TimeDelta operator-(Time other) const {
345 return TimeDelta(us_ - other.us_);
346 }
347
348 // Modify by some time delta.
349 Time& operator+=(TimeDelta delta) {
350 us_ += delta.delta_;
351 return *this;
352 }
353 Time& operator-=(TimeDelta delta) {
354 us_ -= delta.delta_;
355 return *this;
356 }
357
358 // Return a new time modified by some delta.
359 Time operator+(TimeDelta delta) const {
360 return Time(us_ + delta.delta_);
361 }
362 Time operator-(TimeDelta delta) const {
363 return Time(us_ - delta.delta_);
364 }
365
366 // Comparison operators
367 bool operator==(Time other) const {
368 return us_ == other.us_;
369 }
370 bool operator!=(Time other) const {
371 return us_ != other.us_;
372 }
373 bool operator<(Time other) const {
374 return us_ < other.us_;
375 }
376 bool operator<=(Time other) const {
377 return us_ <= other.us_;
378 }
379 bool operator>(Time other) const {
380 return us_ > other.us_;
381 }
382 bool operator>=(Time other) const {
383 return us_ >= other.us_;
384 }
385
386 private:
387 friend class TimeDelta;
388
Time(int64 us)389 explicit Time(int64 us) : us_(us) {
390 }
391
392 // Explodes the given time to either local time |is_local = true| or UTC
393 // |is_local = false|.
394 void Explode(bool is_local, Exploded* exploded) const;
395
396 // Unexplodes a given time assuming the source is either local time
397 // |is_local = true| or UTC |is_local = false|.
398 static Time FromExploded(bool is_local, const Exploded& exploded);
399
400 // The representation of Jan 1, 1970 UTC in microseconds since the
401 // platform-dependent epoch.
402 static const int64 kTimeTToMicrosecondsOffset;
403
404 #if defined(OS_WIN)
405 // Indicates whether fast timers are usable right now. For instance,
406 // when using battery power, we might elect to prevent high speed timers
407 // which would draw more power.
408 static bool high_resolution_timer_enabled_;
409 #endif
410
411 // Time in microseconds in UTC.
412 int64 us_;
413 };
414
415 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
416
417 // static
FromDays(int64 days)418 inline TimeDelta TimeDelta::FromDays(int64 days) {
419 return TimeDelta(days * Time::kMicrosecondsPerDay);
420 }
421
422 // static
FromHours(int64 hours)423 inline TimeDelta TimeDelta::FromHours(int64 hours) {
424 return TimeDelta(hours * Time::kMicrosecondsPerHour);
425 }
426
427 // static
FromMinutes(int64 minutes)428 inline TimeDelta TimeDelta::FromMinutes(int64 minutes) {
429 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
430 }
431
432 // static
FromSeconds(int64 secs)433 inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
434 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
435 }
436
437 // static
FromMilliseconds(int64 ms)438 inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
439 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
440 }
441
442 // static
FromMicroseconds(int64 us)443 inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
444 return TimeDelta(us);
445 }
446
447 inline Time TimeDelta::operator+(Time t) const {
448 return Time(t.us_ + delta_);
449 }
450
451 // TimeTicks ------------------------------------------------------------------
452
453 class BASE_API TimeTicks {
454 public:
TimeTicks()455 TimeTicks() : ticks_(0) {
456 }
457
458 // Platform-dependent tick count representing "right now."
459 // The resolution of this clock is ~1-15ms. Resolution varies depending
460 // on hardware/operating system configuration.
461 static TimeTicks Now();
462
463 // Returns a platform-dependent high-resolution tick count. Implementation
464 // is hardware dependent and may or may not return sub-millisecond
465 // resolution. THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND
466 // SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED.
467 static TimeTicks HighResNow();
468
469 #if defined(OS_WIN)
470 // Get the absolute value of QPC time drift. For testing.
471 static int64 GetQPCDriftMicroseconds();
472
473 // Returns true if the high resolution clock is working on this system.
474 // This is only for testing.
475 static bool IsHighResClockWorking();
476 #endif
477
478 // Returns true if this object has not been initialized.
is_null()479 bool is_null() const {
480 return ticks_ == 0;
481 }
482
483 // Returns the internal numeric value of the TimeTicks object.
ToInternalValue()484 int64 ToInternalValue() const {
485 return ticks_;
486 }
487
488 TimeTicks& operator=(TimeTicks other) {
489 ticks_ = other.ticks_;
490 return *this;
491 }
492
493 // Compute the difference between two times.
494 TimeDelta operator-(TimeTicks other) const {
495 return TimeDelta(ticks_ - other.ticks_);
496 }
497
498 // Modify by some time delta.
499 TimeTicks& operator+=(TimeDelta delta) {
500 ticks_ += delta.delta_;
501 return *this;
502 }
503 TimeTicks& operator-=(TimeDelta delta) {
504 ticks_ -= delta.delta_;
505 return *this;
506 }
507
508 // Return a new TimeTicks modified by some delta.
509 TimeTicks operator+(TimeDelta delta) const {
510 return TimeTicks(ticks_ + delta.delta_);
511 }
512 TimeTicks operator-(TimeDelta delta) const {
513 return TimeTicks(ticks_ - delta.delta_);
514 }
515
516 // Comparison operators
517 bool operator==(TimeTicks other) const {
518 return ticks_ == other.ticks_;
519 }
520 bool operator!=(TimeTicks other) const {
521 return ticks_ != other.ticks_;
522 }
523 bool operator<(TimeTicks other) const {
524 return ticks_ < other.ticks_;
525 }
526 bool operator<=(TimeTicks other) const {
527 return ticks_ <= other.ticks_;
528 }
529 bool operator>(TimeTicks other) const {
530 return ticks_ > other.ticks_;
531 }
532 bool operator>=(TimeTicks other) const {
533 return ticks_ >= other.ticks_;
534 }
535
536 protected:
537 friend class TimeDelta;
538 friend class PageLoadTrackerUnitTest;
539
540 // Please use Now() to create a new object. This is for internal use
541 // and testing. Ticks is in microseconds.
TimeTicks(int64 ticks)542 explicit TimeTicks(int64 ticks) : ticks_(ticks) {
543 }
544
545 // Tick count in microseconds.
546 int64 ticks_;
547
548 #if defined(OS_WIN)
549 typedef DWORD (*TickFunctionType)(void);
550 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
551 #endif
552 };
553
554 inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
555 return TimeTicks(t.ticks_ + delta_);
556 }
557
558 } // namespace base
559
560 #endif // BASE_TIME_H_
561