Wed, 31 Dec 2014 06:09:35 +0100
Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.
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.
9 //
10 // TimeDelta represents a duration of time, internally represented in
11 // microseconds.
12 //
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.
19 //
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_
26 #include <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.
35 #undef TYPE_BOOL
36 #endif
38 #if defined(OS_POSIX)
39 #include <unistd.h>
40 #include <sys/time.h>
41 #endif
43 #if defined(OS_WIN)
44 // For FILETIME in FromFileTime, until it moves to a new converter class.
45 // See TODO(iyengar) below.
46 #include <windows.h>
47 #endif
49 #include <limits>
51 namespace base {
53 class Time;
54 class TimeTicks;
56 // TimeDelta ------------------------------------------------------------------
58 class BASE_EXPORT TimeDelta {
59 public:
60 TimeDelta() : delta_(0) {
61 }
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);
70 #if defined(OS_WIN)
71 static TimeDelta FromQPCValue(LONGLONG qpc_value);
72 #endif
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);
80 }
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 {
87 return delta_;
88 }
90 #if defined(OS_POSIX)
91 struct timespec ToTimeSpec() const;
92 #endif
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.
96 //
97 // InMillisecondsRoundedUp() instead returns an integer that is rounded up
98 // to the next full millisecond.
99 int InDays() const;
100 int InHours() const;
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_;
111 return *this;
112 }
114 // Computations with other deltas.
115 TimeDelta operator+(TimeDelta other) const {
116 return TimeDelta(delta_ + other.delta_);
117 }
118 TimeDelta operator-(TimeDelta other) const {
119 return TimeDelta(delta_ - other.delta_);
120 }
122 TimeDelta& operator+=(TimeDelta other) {
123 delta_ += other.delta_;
124 return *this;
125 }
126 TimeDelta& operator-=(TimeDelta other) {
127 delta_ -= other.delta_;
128 return *this;
129 }
130 TimeDelta operator-() const {
131 return TimeDelta(-delta_);
132 }
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);
138 }
139 TimeDelta operator/(int64 a) const {
140 return TimeDelta(delta_ / a);
141 }
142 TimeDelta& operator*=(int64 a) {
143 delta_ *= a;
144 return *this;
145 }
146 TimeDelta& operator/=(int64 a) {
147 delta_ /= a;
148 return *this;
149 }
150 int64 operator/(TimeDelta a) const {
151 return delta_ / a.delta_;
152 }
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_;
161 }
162 bool operator!=(TimeDelta other) const {
163 return delta_ != other.delta_;
164 }
165 bool operator<(TimeDelta other) const {
166 return delta_ < other.delta_;
167 }
168 bool operator<=(TimeDelta other) const {
169 return delta_ <= other.delta_;
170 }
171 bool operator>(TimeDelta other) const {
172 return delta_ > other.delta_;
173 }
174 bool operator>=(TimeDelta other) const {
175 return delta_ >= other.delta_;
176 }
178 private:
179 friend class Time;
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) {
187 }
189 // Delta in microseconds.
190 int64 delta_;
191 };
193 inline TimeDelta operator*(int64 a, TimeDelta td) {
194 return TimeDelta(a * td.delta_);
195 }
197 // Time -----------------------------------------------------------------------
199 // Represents a wall clock time.
200 class BASE_EXPORT Time {
201 public:
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;
214 #if !defined(OS_WIN)
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
219 // migration code.
220 static const int64 kWindowsEpochDeltaMicroseconds;
221 #endif
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;
241 };
243 // Contains the NULL time. Use Time::Now() to get the current time.
244 Time() : us_(0) {
245 }
247 // Returns true if the time object has not been initialized.
248 bool is_null() const {
249 return us_ == 0;
250 }
252 // Returns true if the time object is the maximum time.
253 bool is_max() const {
254 return us_ == std::numeric_limits<int64>::max();
255 }
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.
263 static Time Now();
265 // Returns the maximum time, which should be greater than any reasonable time
266 // with which we might compare it.
267 static Time Max();
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|
277 // class.
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
285 // initialized".
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);
295 #endif
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;
310 #endif
312 #if defined(OS_MACOSX)
313 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
314 CFAbsoluteTime ToCFAbsoluteTime() const;
315 #endif
317 #if defined(OS_WIN)
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
330 // activations.
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
346 // way.
347 static bool IsHighResolutionTimerInUse();
348 #endif
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);
354 }
355 static Time FromLocalExploded(const Exploded& exploded) {
356 return FromExploded(true, exploded);
357 }
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) {
364 return Time(us);
365 }
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);
377 }
378 static bool FromUTCString(const char* time_string, Time* parsed_time) {
379 return FromStringInternal(time_string, false, parsed_time);
380 }
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 {
386 return us_;
387 }
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);
393 }
394 void LocalExplode(Exploded* exploded) const {
395 return Explode(true, exploded);
396 }
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) {
403 us_ = other.us_;
404 return *this;
405 }
407 // Compute the difference between two times.
408 TimeDelta operator-(Time other) const {
409 return TimeDelta(us_ - other.us_);
410 }
412 // Modify by some time delta.
413 Time& operator+=(TimeDelta delta) {
414 us_ += delta.delta_;
415 return *this;
416 }
417 Time& operator-=(TimeDelta delta) {
418 us_ -= delta.delta_;
419 return *this;
420 }
422 // Return a new time modified by some delta.
423 Time operator+(TimeDelta delta) const {
424 return Time(us_ + delta.delta_);
425 }
426 Time operator-(TimeDelta delta) const {
427 return Time(us_ - delta.delta_);
428 }
430 // Comparison operators
431 bool operator==(Time other) const {
432 return us_ == other.us_;
433 }
434 bool operator!=(Time other) const {
435 return us_ != other.us_;
436 }
437 bool operator<(Time other) const {
438 return us_ < other.us_;
439 }
440 bool operator<=(Time other) const {
441 return us_ <= other.us_;
442 }
443 bool operator>(Time other) const {
444 return us_ > other.us_;
445 }
446 bool operator>=(Time other) const {
447 return us_ >= other.us_;
448 }
450 private:
451 friend class TimeDelta;
453 explicit Time(int64 us) : us_(us) {
454 }
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,
472 bool is_local,
473 Time* parsed_time);
475 // The representation of Jan 1, 1970 UTC in microseconds since the
476 // platform-dependent epoch.
477 static const int64 kTimeTToMicrosecondsOffset;
479 #if defined(OS_WIN)
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_;
487 #endif
489 // Time in microseconds in UTC.
490 int64 us_;
491 };
493 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
495 // static
496 inline TimeDelta TimeDelta::FromDays(int64 days) {
497 return TimeDelta(days * Time::kMicrosecondsPerDay);
498 }
500 // static
501 inline TimeDelta TimeDelta::FromHours(int64 hours) {
502 return TimeDelta(hours * Time::kMicrosecondsPerHour);
503 }
505 // static
506 inline TimeDelta TimeDelta::FromMinutes(int64 minutes) {
507 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
508 }
510 // static
511 inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
512 return TimeDelta(secs * Time::kMicrosecondsPerSecond);
513 }
515 // static
516 inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
517 return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
518 }
520 // static
521 inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
522 return TimeDelta(us);
523 }
525 inline Time TimeDelta::operator+(Time t) const {
526 return Time(t.us_ + delta_);
527 }
529 // TimeTicks ------------------------------------------------------------------
531 class BASE_EXPORT TimeTicks {
532 public:
533 TimeTicks() : ticks_(0) {
534 }
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 // Returns true if ThreadNow() is supported on this system.
548 static bool IsThreadNowSupported() {
549 #if defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)
550 return true;
551 #else
552 return false;
553 #endif
554 }
556 // Returns thread-specific CPU-time on systems that support this feature.
557 // Needs to be guarded with a call to IsThreadNowSupported(). Use this timer
558 // to (approximately) measure how much time the calling thread spent doing
559 // actual work vs. being de-scheduled. May return bogus results if the thread
560 // migrates to another CPU between two calls.
561 static TimeTicks ThreadNow();
563 // Returns the current system trace time or, if none is defined, the current
564 // high-res time (i.e. HighResNow()). On systems where a global trace clock
565 // is defined, timestamping TraceEvents's with this value guarantees
566 // synchronization between events collected inside chrome and events
567 // collected outside (e.g. kernel, X server).
568 static TimeTicks NowFromSystemTraceTime();
570 #if defined(OS_WIN)
571 // Get the absolute value of QPC time drift. For testing.
572 static int64 GetQPCDriftMicroseconds();
574 static TimeTicks FromQPCValue(LONGLONG qpc_value);
576 // Returns true if the high resolution clock is working on this system.
577 // This is only for testing.
578 static bool IsHighResClockWorking();
580 // Enable high resolution time for TimeTicks::Now(). This function will
581 // test for the availability of a working implementation of
582 // QueryPerformanceCounter(). If one is not available, this function does
583 // nothing and the resolution of Now() remains 1ms. Otherwise, all future
584 // calls to TimeTicks::Now() will have the higher resolution provided by QPC.
585 // Returns true if high resolution time was successfully enabled.
586 static bool SetNowIsHighResNowIfSupported();
588 // Returns a time value that is NOT rollover protected.
589 static TimeTicks UnprotectedNow();
590 #endif
592 // Returns true if this object has not been initialized.
593 bool is_null() const {
594 return ticks_ == 0;
595 }
597 // Converts an integer value representing TimeTicks to a class. This is used
598 // when deserializing a |TimeTicks| structure, using a value known to be
599 // compatible. It is not provided as a constructor because the integer type
600 // may be unclear from the perspective of a caller.
601 static TimeTicks FromInternalValue(int64 ticks) {
602 return TimeTicks(ticks);
603 }
605 // Returns the internal numeric value of the TimeTicks object.
606 // For serializing, use FromInternalValue to reconstitute.
607 int64 ToInternalValue() const {
608 return ticks_;
609 }
611 TimeTicks& operator=(TimeTicks other) {
612 ticks_ = other.ticks_;
613 return *this;
614 }
616 // Compute the difference between two times.
617 TimeDelta operator-(TimeTicks other) const {
618 return TimeDelta(ticks_ - other.ticks_);
619 }
621 // Modify by some time delta.
622 TimeTicks& operator+=(TimeDelta delta) {
623 ticks_ += delta.delta_;
624 return *this;
625 }
626 TimeTicks& operator-=(TimeDelta delta) {
627 ticks_ -= delta.delta_;
628 return *this;
629 }
631 // Return a new TimeTicks modified by some delta.
632 TimeTicks operator+(TimeDelta delta) const {
633 return TimeTicks(ticks_ + delta.delta_);
634 }
635 TimeTicks operator-(TimeDelta delta) const {
636 return TimeTicks(ticks_ - delta.delta_);
637 }
639 // Comparison operators
640 bool operator==(TimeTicks other) const {
641 return ticks_ == other.ticks_;
642 }
643 bool operator!=(TimeTicks other) const {
644 return ticks_ != other.ticks_;
645 }
646 bool operator<(TimeTicks other) const {
647 return ticks_ < other.ticks_;
648 }
649 bool operator<=(TimeTicks other) const {
650 return ticks_ <= other.ticks_;
651 }
652 bool operator>(TimeTicks other) const {
653 return ticks_ > other.ticks_;
654 }
655 bool operator>=(TimeTicks other) const {
656 return ticks_ >= other.ticks_;
657 }
659 protected:
660 friend class TimeDelta;
662 // Please use Now() to create a new object. This is for internal use
663 // and testing. Ticks is in microseconds.
664 explicit TimeTicks(int64 ticks) : ticks_(ticks) {
665 }
667 // Tick count in microseconds.
668 int64 ticks_;
670 #if defined(OS_WIN)
671 typedef DWORD (*TickFunctionType)(void);
672 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
673 #endif
674 };
676 inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
677 return TimeTicks(t.ticks_ + delta_);
678 }
680 } // namespace base
682 #endif // BASE_TIME_TIME_H_