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.
4
5// Time represents an absolute point in coordinated universal time (UTC),
6// internally represented as microseconds (s/1,000,000) since the Windows epoch
7// (1601-01-01 00:00:00 UTC). System-dependent clock interface routines are
8// defined in time_PLATFORM.cc. Note that values for Time may skew and jump
9// around as the operating system makes adjustments to synchronize (e.g., with
10// NTP servers). Thus, client code that uses the Time class must account for
11// this.
12//
13// TimeDelta represents a duration of time, internally represented in
14// microseconds.
15//
16// TimeTicks and ThreadTicks represent an abstract time that is most of the time
17// incrementing, for use in measuring time durations. Internally, they are
18// represented in microseconds. They cannot be converted to a human-readable
19// time, but are guaranteed not to decrease (unlike the Time class). Note that
20// TimeTicks may "stand still" (e.g., if the computer is suspended), and
21// ThreadTicks will "stand still" whenever the thread has been de-scheduled by
22// the operating system.
23//
24// All time classes are copyable, assignable, and occupy 64-bits per instance.
25// As a result, prefer passing them by value:
26// void MyFunction(TimeDelta arg);
27// If circumstances require, you may also pass by const reference:
28// void MyFunction(const TimeDelta& arg); // Not preferred.
29//
30// Definitions of operator<< are provided to make these types work with
31// DCHECK_EQ() and other log macros. For human-readable formatting, see
32// "base/i18n/time_formatting.h".
33//
34// So many choices! Which time class should you use? Examples:
35//
36// Time: Interpreting the wall-clock time provided by a remote system.
37// Detecting whether cached resources have expired. Providing the
38// user with a display of the current date and time. Determining
39// the amount of time between events across re-boots of the
40// machine.
41//
42// TimeTicks: Tracking the amount of time a task runs. Executing delayed
43// tasks at the right time. Computing presentation timestamps.
44// Synchronizing audio and video using TimeTicks as a common
45// reference clock (lip-sync). Measuring network round-trip
46// latency.
47//
48// ThreadTicks: Benchmarking how long the current thread has been doing actual
49// work.
50
51#ifndef BASE_TIME_TIME_H_
52#define BASE_TIME_TIME_H_
53
54#include <stdint.h>
55#include <time.h>
56
57#include <iosfwd>
58#include <limits>
59
60#include "base/base_export.h"
61#include "base/compiler_specific.h"
62#include "base/logging.h"
63#include "base/numerics/safe_math.h"
64#include "build/build_config.h"
65
66#if defined(OS_FUCHSIA)
67#include <zircon/types.h>
68#endif
69
70#if defined(OS_MACOSX)
71#include <CoreFoundation/CoreFoundation.h>
72// Avoid Mac system header macro leak.
73#undef TYPE_BOOL
74#endif
75
76#if defined(OS_ANDROID)
77#include <jni.h>
78#endif
79
80#if defined(OS_POSIX) || defined(OS_FUCHSIA)
81#include <unistd.h>
82#include <sys/time.h>
83#endif
84
85#if defined(OS_WIN)
86#include "base/gtest_prod_util.h"
87#include "base/win/windows_types.h"
88#endif
89
90namespace base {
91
92class PlatformThreadHandle;
93class TimeDelta;
94
95// The functions in the time_internal namespace are meant to be used only by the
96// time classes and functions. Please use the math operators defined in the
97// time classes instead.
98namespace time_internal {
99
100// Add or subtract a TimeDelta from |value|. TimeDelta::Min()/Max() are treated
101// as infinity and will always saturate the return value (infinity math applies
102// if |value| also is at either limit of its spectrum). The int64_t argument and
103// return value are in terms of a microsecond timebase.
104BASE_EXPORT int64_t SaturatedAdd(int64_t value, TimeDelta delta);
105BASE_EXPORT int64_t SaturatedSub(int64_t value, TimeDelta delta);
106
107} // namespace time_internal
108
109// TimeDelta ------------------------------------------------------------------
110
111class BASE_EXPORT TimeDelta {
112 public:
113 constexpr TimeDelta() : delta_(0) {}
114
115 // Converts units of time to TimeDeltas.
116 static constexpr TimeDelta FromDays(int days);
117 static constexpr TimeDelta FromHours(int hours);
118 static constexpr TimeDelta FromMinutes(int minutes);
119 static constexpr TimeDelta FromSeconds(int64_t secs);
120 static constexpr TimeDelta FromMilliseconds(int64_t ms);
121 static constexpr TimeDelta FromMicroseconds(int64_t us);
122 static constexpr TimeDelta FromNanoseconds(int64_t ns);
123 static constexpr TimeDelta FromSecondsD(double secs);
124 static constexpr TimeDelta FromMillisecondsD(double ms);
125 static constexpr TimeDelta FromMicrosecondsD(double us);
126 static constexpr TimeDelta FromNanosecondsD(double ns);
127#if defined(OS_WIN)
128 static TimeDelta FromQPCValue(LONGLONG qpc_value);
129 static TimeDelta FromFileTime(FILETIME ft);
130#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
131 static TimeDelta FromTimeSpec(const timespec& ts);
132#endif
133
134 // Converts an integer value representing TimeDelta to a class. This is used
135 // when deserializing a |TimeDelta| structure, using a value known to be
136 // compatible. It is not provided as a constructor because the integer type
137 // may be unclear from the perspective of a caller.
138 //
139 // DEPRECATED - Do not use in new code. http://crbug.com/634507
140 static constexpr TimeDelta FromInternalValue(int64_t delta) {
141 return TimeDelta(delta);
142 }
143
144 // Returns the maximum time delta, which should be greater than any reasonable
145 // time delta we might compare it to. Adding or subtracting the maximum time
146 // delta to a time or another time delta has an undefined result.
147 static constexpr TimeDelta Max();
148
149 // Returns the minimum time delta, which should be less than than any
150 // reasonable time delta we might compare it to. Adding or subtracting the
151 // minimum time delta to a time or another time delta has an undefined result.
152 static constexpr TimeDelta Min();
153
154 // Returns the internal numeric value of the TimeDelta object. Please don't
155 // use this and do arithmetic on it, as it is more error prone than using the
156 // provided operators.
157 // For serializing, use FromInternalValue to reconstitute.
158 //
159 // DEPRECATED - Do not use in new code. http://crbug.com/634507
160 constexpr int64_t ToInternalValue() const { return delta_; }
161
162 // Returns the magnitude (absolute value) of this TimeDelta.
163 constexpr TimeDelta magnitude() const {
164 // Some toolchains provide an incomplete C++11 implementation and lack an
165 // int64_t overload for std::abs(). The following is a simple branchless
166 // implementation:
167 const int64_t mask = delta_ >> (sizeof(delta_) * 8 - 1);
168 return TimeDelta((delta_ + mask) ^ mask);
169 }
170
171 // Returns true if the time delta is zero.
172 constexpr bool is_zero() const { return delta_ == 0; }
173
174 // Returns true if the time delta is the maximum/minimum time delta.
175 constexpr bool is_max() const {
176 return delta_ == std::numeric_limits<int64_t>::max();
177 }
178 constexpr bool is_min() const {
179 return delta_ == std::numeric_limits<int64_t>::min();
180 }
181
182#if defined(OS_POSIX) || defined(OS_FUCHSIA)
183 struct timespec ToTimeSpec() const;
184#endif
185
186 // Returns the time delta in some unit. The InXYZF versions return a floating
187 // point value. The InXYZ versions return a truncated value (aka rounded
188 // towards zero, std::trunc() behavior). The InXYZFloored() versions round to
189 // lesser integers (std::floor() behavior). The XYZRoundedUp() versions round
190 // up to greater integers (std::ceil() behavior).
191 int InDays() const;
192 int InDaysFloored() const;
193 int InHours() const;
194 int InMinutes() const;
195 double InSecondsF() const;
196 int64_t InSeconds() const;
197 double InMillisecondsF() const;
198 int64_t InMilliseconds() const;
199 int64_t InMillisecondsRoundedUp() const;
200 constexpr int64_t InMicroseconds() const { return delta_; }
201 double InMicrosecondsF() const;
202 int64_t InNanoseconds() const;
203
204 // Computations with other deltas. Can easily be made constexpr with C++17 but
205 // hard to do until then per limitations around
206 // __builtin_(add|sub)_overflow in safe_math_clang_gcc_impl.h :
207 // https://chromium-review.googlesource.com/c/chromium/src/+/873352#message-59594ab70827795a67e0780404adf37b4b6c2f14
208 TimeDelta operator+(TimeDelta other) const {
209 return TimeDelta(time_internal::SaturatedAdd(delta_, other));
210 }
211 TimeDelta operator-(TimeDelta other) const {
212 return TimeDelta(time_internal::SaturatedSub(delta_, other));
213 }
214
215 TimeDelta& operator+=(TimeDelta other) {
216 return *this = (*this + other);
217 }
218 TimeDelta& operator-=(TimeDelta other) {
219 return *this = (*this - other);
220 }
221 constexpr TimeDelta operator-() const { return TimeDelta(-delta_); }
222
223 // Computations with numeric types. operator*() isn't constexpr because of a
224 // limitation around __builtin_mul_overflow (but operator/(1.0/a) works for
225 // |a|'s of "reasonable" size -- i.e. that don't risk overflow).
226 template <typename T>
227 TimeDelta operator*(T a) const {
228 CheckedNumeric<int64_t> rv(delta_);
229 rv *= a;
230 if (rv.IsValid())
231 return TimeDelta(rv.ValueOrDie());
232 // Matched sign overflows. Mismatched sign underflows.
233 if ((delta_ < 0) ^ (a < 0))
234 return TimeDelta(std::numeric_limits<int64_t>::min());
235 return TimeDelta(std::numeric_limits<int64_t>::max());
236 }
237 template <typename T>
238 constexpr TimeDelta operator/(T a) const {
239 CheckedNumeric<int64_t> rv(delta_);
240 rv /= a;
241 if (rv.IsValid())
242 return TimeDelta(rv.ValueOrDie());
243 // Matched sign overflows. Mismatched sign underflows.
244 // Special case to catch divide by zero.
245 if ((delta_ < 0) ^ (a <= 0))
246 return TimeDelta(std::numeric_limits<int64_t>::min());
247 return TimeDelta(std::numeric_limits<int64_t>::max());
248 }
249 template <typename T>
250 TimeDelta& operator*=(T a) {
251 return *this = (*this * a);
252 }
253 template <typename T>
254 constexpr TimeDelta& operator/=(T a) {
255 return *this = (*this / a);
256 }
257
258 constexpr int64_t operator/(TimeDelta a) const { return delta_ / a.delta_; }
259 constexpr TimeDelta operator%(TimeDelta a) const {
260 return TimeDelta(delta_ % a.delta_);
261 }
262
263 // Comparison operators.
264 constexpr bool operator==(TimeDelta other) const {
265 return delta_ == other.delta_;
266 }
267 constexpr bool operator!=(TimeDelta other) const {
268 return delta_ != other.delta_;
269 }
270 constexpr bool operator<(TimeDelta other) const {
271 return delta_ < other.delta_;
272 }
273 constexpr bool operator<=(TimeDelta other) const {
274 return delta_ <= other.delta_;
275 }
276 constexpr bool operator>(TimeDelta other) const {
277 return delta_ > other.delta_;
278 }
279 constexpr bool operator>=(TimeDelta other) const {
280 return delta_ >= other.delta_;
281 }
282
283 private:
284 friend int64_t time_internal::SaturatedAdd(int64_t value, TimeDelta delta);
285 friend int64_t time_internal::SaturatedSub(int64_t value, TimeDelta delta);
286
287 // Constructs a delta given the duration in microseconds. This is private
288 // to avoid confusion by callers with an integer constructor. Use
289 // FromSeconds, FromMilliseconds, etc. instead.
290 constexpr explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {}
291
292 // Private method to build a delta from a double.
293 static constexpr TimeDelta FromDouble(double value);
294
295 // Private method to build a delta from the product of a user-provided value
296 // and a known-positive value.
297 static constexpr TimeDelta FromProduct(int64_t value, int64_t positive_value);
298
299 // Delta in microseconds.
300 int64_t delta_;
301};
302
303template <typename T>
304TimeDelta operator*(T a, TimeDelta td) {
305 return td * a;
306}
307
308// For logging use only.
309BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
310
311// Do not reference the time_internal::TimeBase template class directly. Please
312// use one of the time subclasses instead, and only reference the public
313// TimeBase members via those classes.
314namespace time_internal {
315
316// TimeBase--------------------------------------------------------------------
317
318// Provides value storage and comparison/math operations common to all time
319// classes. Each subclass provides for strong type-checking to ensure
320// semantically meaningful comparison/math of time values from the same clock
321// source or timeline.
322template<class TimeClass>
323class TimeBase {
324 public:
325 static constexpr int64_t kHoursPerDay = 24;
326 static constexpr int64_t kSecondsPerMinute = 60;
327 static constexpr int64_t kSecondsPerHour = 60 * kSecondsPerMinute;
328 static constexpr int64_t kMillisecondsPerSecond = 1000;
329 static constexpr int64_t kMillisecondsPerDay =
330 kMillisecondsPerSecond * 60 * 60 * kHoursPerDay;
331 static constexpr int64_t kMicrosecondsPerMillisecond = 1000;
332 static constexpr int64_t kMicrosecondsPerSecond =
333 kMicrosecondsPerMillisecond * kMillisecondsPerSecond;
334 static constexpr int64_t kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
335 static constexpr int64_t kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
336 static constexpr int64_t kMicrosecondsPerDay =
337 kMicrosecondsPerHour * kHoursPerDay;
338 static constexpr int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
339 static constexpr int64_t kNanosecondsPerMicrosecond = 1000;
340 static constexpr int64_t kNanosecondsPerSecond =
341 kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
342
343 // Returns true if this object has not been initialized.
344 //
345 // Warning: Be careful when writing code that performs math on time values,
346 // since it's possible to produce a valid "zero" result that should not be
347 // interpreted as a "null" value.
348 constexpr bool is_null() const { return us_ == 0; }
349
350 // Returns true if this object represents the maximum/minimum time.
351 constexpr bool is_max() const {
352 return us_ == std::numeric_limits<int64_t>::max();
353 }
354 constexpr bool is_min() const {
355 return us_ == std::numeric_limits<int64_t>::min();
356 }
357
358 // Returns the maximum/minimum times, which should be greater/less than than
359 // any reasonable time with which we might compare it.
360 static TimeClass Max() {
361 return TimeClass(std::numeric_limits<int64_t>::max());
362 }
363
364 static TimeClass Min() {
365 return TimeClass(std::numeric_limits<int64_t>::min());
366 }
367
368 // For serializing only. Use FromInternalValue() to reconstitute. Please don't
369 // use this and do arithmetic on it, as it is more error prone than using the
370 // provided operators.
371 //
372 // DEPRECATED - Do not use in new code. For serializing Time values, prefer
373 // Time::ToDeltaSinceWindowsEpoch().InMicroseconds(). http://crbug.com/634507
374 constexpr int64_t ToInternalValue() const { return us_; }
375
376 // The amount of time since the origin (or "zero") point. This is a syntactic
377 // convenience to aid in code readability, mainly for debugging/testing use
378 // cases.
379 //
380 // Warning: While the Time subclass has a fixed origin point, the origin for
381 // the other subclasses can vary each time the application is restarted.
382 constexpr TimeDelta since_origin() const {
383 return TimeDelta::FromMicroseconds(us_);
384 }
385
386 TimeClass& operator=(TimeClass other) {
387 us_ = other.us_;
388 return *(static_cast<TimeClass*>(this));
389 }
390
391 // Compute the difference between two times.
392 TimeDelta operator-(TimeClass other) const {
393 return TimeDelta::FromMicroseconds(us_ - other.us_);
394 }
395
396 // Return a new time modified by some delta.
397 TimeClass operator+(TimeDelta delta) const {
398 return TimeClass(time_internal::SaturatedAdd(us_, delta));
399 }
400 TimeClass operator-(TimeDelta delta) const {
401 return TimeClass(time_internal::SaturatedSub(us_, delta));
402 }
403
404 // Modify by some time delta.
405 TimeClass& operator+=(TimeDelta delta) {
406 return static_cast<TimeClass&>(*this = (*this + delta));
407 }
408 TimeClass& operator-=(TimeDelta delta) {
409 return static_cast<TimeClass&>(*this = (*this - delta));
410 }
411
412 // Comparison operators
413 bool operator==(TimeClass other) const {
414 return us_ == other.us_;
415 }
416 bool operator!=(TimeClass other) const {
417 return us_ != other.us_;
418 }
419 bool operator<(TimeClass other) const {
420 return us_ < other.us_;
421 }
422 bool operator<=(TimeClass other) const {
423 return us_ <= other.us_;
424 }
425 bool operator>(TimeClass other) const {
426 return us_ > other.us_;
427 }
428 bool operator>=(TimeClass other) const {
429 return us_ >= other.us_;
430 }
431
432 protected:
433 constexpr explicit TimeBase(int64_t us) : us_(us) {}
434
435 // Time value in a microsecond timebase.
436 int64_t us_;
437};
438
439} // namespace time_internal
440
441template<class TimeClass>
442inline TimeClass operator+(TimeDelta delta, TimeClass t) {
443 return t + delta;
444}
445
446// Time -----------------------------------------------------------------------
447
448// Represents a wall clock time in UTC. Values are not guaranteed to be
449// monotonically non-decreasing and are subject to large amounts of skew.
450class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
451 public:
452 // Offset of UNIX epoch (1970-01-01 00:00:00 UTC) from Windows FILETIME epoch
453 // (1601-01-01 00:00:00 UTC), in microseconds. This value is derived from the
454 // following: ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the number
455 // of leap year days between 1601 and 1970: (1970-1601)/4 excluding 1700,
456 // 1800, and 1900.
457 static constexpr int64_t kTimeTToMicrosecondsOffset =
458 INT64_C(11644473600000000);
459
460#if defined(OS_WIN)
461 // To avoid overflow in QPC to Microseconds calculations, since we multiply
462 // by kMicrosecondsPerSecond, then the QPC value should not exceed
463 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
464 static constexpr int64_t kQPCOverflowThreshold = INT64_C(0x8637BD05AF7);
465#endif
466
467// kExplodedMinYear and kExplodedMaxYear define the platform-specific limits
468// for values passed to FromUTCExploded() and FromLocalExploded(). Those
469// functions will return false if passed values outside these limits. The limits
470// are inclusive, meaning that the API should support all dates within a given
471// limit year.
472#if defined(OS_WIN)
473 static constexpr int kExplodedMinYear = 1601;
474 static constexpr int kExplodedMaxYear = 30827;
475#elif defined(OS_IOS)
476 static constexpr int kExplodedMinYear = std::numeric_limits<int>::min();
477 static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
478#elif defined(OS_MACOSX)
479 static constexpr int kExplodedMinYear = 1902;
480 static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
481#elif defined(OS_ANDROID)
482 // Though we use 64-bit time APIs on both 32 and 64 bit Android, some OS
483 // versions like KitKat (ARM but not x86 emulator) can't handle some early
484 // dates (e.g. before 1170). So we set min conservatively here.
485 static constexpr int kExplodedMinYear = 1902;
486 static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
487#else
488 static constexpr int kExplodedMinYear =
489 (sizeof(time_t) == 4 ? 1902 : std::numeric_limits<int>::min());
490 static constexpr int kExplodedMaxYear =
491 (sizeof(time_t) == 4 ? 2037 : std::numeric_limits<int>::max());
492#endif
493
494 // Represents an exploded time that can be formatted nicely. This is kind of
495 // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
496 // additions and changes to prevent errors.
497 struct BASE_EXPORT Exploded {
498 int year; // Four digit year "2007"
499 int month; // 1-based month (values 1 = January, etc.)
500 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
501 int day_of_month; // 1-based day of month (1-31)
502 int hour; // Hour within the current day (0-23)
503 int minute; // Minute within the current hour (0-59)
504 int second; // Second within the current minute (0-59 plus leap
505 // seconds which may take it up to 60).
506 int millisecond; // Milliseconds within the current second (0-999)
507
508 // A cursory test for whether the data members are within their
509 // respective ranges. A 'true' return value does not guarantee the
510 // Exploded value can be successfully converted to a Time value.
511 bool HasValidValues() const;
512 };
513
514 // Contains the NULL time. Use Time::Now() to get the current time.
515 constexpr Time() : TimeBase(0) {}
516
517 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
518 static Time UnixEpoch();
519
520 // Returns the current time. Watch out, the system might adjust its clock
521 // in which case time will actually go backwards. We don't guarantee that
522 // times are increasing, or that two calls to Now() won't be the same.
523 static Time Now();
524
525 // Returns the current time. Same as Now() except that this function always
526 // uses system time so that there are no discrepancies between the returned
527 // time and system time even on virtual environments including our test bot.
528 // For timing sensitive unittests, this function should be used.
529 static Time NowFromSystemTime();
530
531 // Converts to/from TimeDeltas relative to the Windows epoch (1601-01-01
532 // 00:00:00 UTC). Prefer these methods for opaque serialization and
533 // deserialization of time values, e.g.
534 //
535 // // Serialization:
536 // base::Time last_updated = ...;
537 // SaveToDatabase(last_updated.ToDeltaSinceWindowsEpoch().InMicroseconds());
538 //
539 // // Deserialization:
540 // base::Time last_updated = base::Time::FromDeltaSinceWindowsEpoch(
541 // base::TimeDelta::FromMicroseconds(LoadFromDatabase()));
542 static Time FromDeltaSinceWindowsEpoch(TimeDelta delta);
543 TimeDelta ToDeltaSinceWindowsEpoch() const;
544
545 // Converts to/from time_t in UTC and a Time class.
546 static Time FromTimeT(time_t tt);
547 time_t ToTimeT() const;
548
549 // Converts time to/from a double which is the number of seconds since epoch
550 // (Jan 1, 1970). Webkit uses this format to represent time.
551 // Because WebKit initializes double time value to 0 to indicate "not
552 // initialized", we map it to empty Time object that also means "not
553 // initialized".
554 static Time FromDoubleT(double dt);
555 double ToDoubleT() const;
556
557#if defined(OS_POSIX) || defined(OS_FUCHSIA)
558 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
559 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
560 // having a 1 second resolution, which agrees with
561 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
562 static Time FromTimeSpec(const timespec& ts);
563#endif
564
565 // Converts to/from the Javascript convention for times, a number of
566 // milliseconds since the epoch:
567 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
568 static Time FromJsTime(double ms_since_epoch);
569 double ToJsTime() const;
570
571 // Converts to/from Java convention for times, a number of milliseconds since
572 // the epoch. Because the Java format has less resolution, converting to Java
573 // time is a lossy operation.
574 static Time FromJavaTime(int64_t ms_since_epoch);
575 int64_t ToJavaTime() const;
576
577#if defined(OS_POSIX) || defined(OS_FUCHSIA)
578 static Time FromTimeVal(struct timeval t);
579 struct timeval ToTimeVal() const;
580#endif
581
582#if defined(OS_MACOSX)
583 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
584 CFAbsoluteTime ToCFAbsoluteTime() const;
585#endif
586
587#if defined(OS_WIN)
588 static Time FromFileTime(FILETIME ft);
589 FILETIME ToFileTime() const;
590
591 // The minimum time of a low resolution timer. This is basically a windows
592 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
593 // treat it as static across all windows versions.
594 static const int kMinLowResolutionThresholdMs = 16;
595
596 // Enable or disable Windows high resolution timer.
597 static void EnableHighResolutionTimer(bool enable);
598
599 // Activates or deactivates the high resolution timer based on the |activate|
600 // flag. If the HighResolutionTimer is not Enabled (see
601 // EnableHighResolutionTimer), this function will return false. Otherwise
602 // returns true. Each successful activate call must be paired with a
603 // subsequent deactivate call.
604 // All callers to activate the high resolution timer must eventually call
605 // this function to deactivate the high resolution timer.
606 static bool ActivateHighResolutionTimer(bool activate);
607
608 // Returns true if the high resolution timer is both enabled and activated.
609 // This is provided for testing only, and is not tracked in a thread-safe
610 // way.
611 static bool IsHighResolutionTimerInUse();
612
613 // The following two functions are used to report the fraction of elapsed time
614 // that the high resolution timer is activated.
615 // ResetHighResolutionTimerUsage() resets the cumulative usage and starts the
616 // measurement interval and GetHighResolutionTimerUsage() returns the
617 // percentage of time since the reset that the high resolution timer was
618 // activated.
619 // ResetHighResolutionTimerUsage() must be called at least once before calling
620 // GetHighResolutionTimerUsage(); otherwise the usage result would be
621 // undefined.
622 static void ResetHighResolutionTimerUsage();
623 static double GetHighResolutionTimerUsage();
624#endif // defined(OS_WIN)
625
626 // Converts an exploded structure representing either the local time or UTC
627 // into a Time class. Returns false on a failure when, for example, a day of
628 // month is set to 31 on a 28-30 day month. Returns Time(0) on overflow.
629 static bool FromUTCExploded(const Exploded& exploded,
630 Time* time) WARN_UNUSED_RESULT {
631 return FromExploded(false, exploded, time);
632 }
633 static bool FromLocalExploded(const Exploded& exploded,
634 Time* time) WARN_UNUSED_RESULT {
635 return FromExploded(true, exploded, time);
636 }
637
638 // Converts a string representation of time to a Time object.
639 // An example of a time string which is converted is as below:-
640 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
641 // in the input string, FromString assumes local time and FromUTCString
642 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
643 // specified in RFC822) is treated as if the timezone is not specified.
644 //
645 // WARNING: the underlying converter is very permissive. For example: it is
646 // not checked whether a given day of the week matches the date; Feb 29
647 // silently becomes Mar 1 in non-leap years; under certain conditions, whole
648 // English sentences may be parsed successfully and yield unexpected results.
649 //
650 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
651 // a new time converter class.
652 static bool FromString(const char* time_string,
653 Time* parsed_time) WARN_UNUSED_RESULT {
654 return FromStringInternal(time_string, true, parsed_time);
655 }
656 static bool FromUTCString(const char* time_string,
657 Time* parsed_time) WARN_UNUSED_RESULT {
658 return FromStringInternal(time_string, false, parsed_time);
659 }
660
661 // Fills the given exploded structure with either the local time or UTC from
662 // this time structure (containing UTC).
663 void UTCExplode(Exploded* exploded) const {
664 return Explode(false, exploded);
665 }
666 void LocalExplode(Exploded* exploded) const {
667 return Explode(true, exploded);
668 }
669
670 // The following two functions round down the time to the nearest day in
671 // either UTC or local time. It will represent midnight on that day.
672 Time UTCMidnight() const { return Midnight(false); }
673 Time LocalMidnight() const { return Midnight(true); }
674
675 // Converts an integer value representing Time to a class. This may be used
676 // when deserializing a |Time| structure, using a value known to be
677 // compatible. It is not provided as a constructor because the integer type
678 // may be unclear from the perspective of a caller.
679 //
680 // DEPRECATED - Do not use in new code. For deserializing Time values, prefer
681 // Time::FromDeltaSinceWindowsEpoch(). http://crbug.com/634507
682 static constexpr Time FromInternalValue(int64_t us) { return Time(us); }
683
684 private:
685 friend class time_internal::TimeBase<Time>;
686
687 constexpr explicit Time(int64_t us) : TimeBase(us) {}
688
689 // Explodes the given time to either local time |is_local = true| or UTC
690 // |is_local = false|.
691 void Explode(bool is_local, Exploded* exploded) const;
692
693 // Unexplodes a given time assuming the source is either local time
694 // |is_local = true| or UTC |is_local = false|. Function returns false on
695 // failure and sets |time| to Time(0). Otherwise returns true and sets |time|
696 // to non-exploded time.
697 static bool FromExploded(bool is_local,
698 const Exploded& exploded,
699 Time* time) WARN_UNUSED_RESULT;
700
701 // Rounds down the time to the nearest day in either local time
702 // |is_local = true| or UTC |is_local = false|.
703 Time Midnight(bool is_local) const;
704
705 // Converts a string representation of time to a Time object.
706 // An example of a time string which is converted is as below:-
707 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
708 // in the input string, local time |is_local = true| or
709 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
710 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
711 // timezone is not specified.
712 static bool FromStringInternal(const char* time_string,
713 bool is_local,
714 Time* parsed_time) WARN_UNUSED_RESULT;
715
716 // Comparison does not consider |day_of_week| when doing the operation.
717 static bool ExplodedMostlyEquals(const Exploded& lhs,
718 const Exploded& rhs) WARN_UNUSED_RESULT;
719};
720
721// static
722constexpr TimeDelta TimeDelta::FromDays(int days) {
723 return days == std::numeric_limits<int>::max()
724 ? Max()
725 : TimeDelta(days * Time::kMicrosecondsPerDay);
726}
727
728// static
729constexpr TimeDelta TimeDelta::FromHours(int hours) {
730 return hours == std::numeric_limits<int>::max()
731 ? Max()
732 : TimeDelta(hours * Time::kMicrosecondsPerHour);
733}
734
735// static
736constexpr TimeDelta TimeDelta::FromMinutes(int minutes) {
737 return minutes == std::numeric_limits<int>::max()
738 ? Max()
739 : TimeDelta(minutes * Time::kMicrosecondsPerMinute);
740}
741
742// static
743constexpr TimeDelta TimeDelta::FromSeconds(int64_t secs) {
744 return FromProduct(secs, Time::kMicrosecondsPerSecond);
745}
746
747// static
748constexpr TimeDelta TimeDelta::FromMilliseconds(int64_t ms) {
749 return FromProduct(ms, Time::kMicrosecondsPerMillisecond);
750}
751
752// static
753constexpr TimeDelta TimeDelta::FromMicroseconds(int64_t us) {
754 return TimeDelta(us);
755}
756
757// static
758constexpr TimeDelta TimeDelta::FromNanoseconds(int64_t ns) {
759 return TimeDelta(ns / Time::kNanosecondsPerMicrosecond);
760}
761
762// static
763constexpr TimeDelta TimeDelta::FromSecondsD(double secs) {
764 return FromDouble(secs * Time::kMicrosecondsPerSecond);
765}
766
767// static
768constexpr TimeDelta TimeDelta::FromMillisecondsD(double ms) {
769 return FromDouble(ms * Time::kMicrosecondsPerMillisecond);
770}
771
772// static
773constexpr TimeDelta TimeDelta::FromMicrosecondsD(double us) {
774 return FromDouble(us);
775}
776
777// static
778constexpr TimeDelta TimeDelta::FromNanosecondsD(double ns) {
779 return FromDouble(ns / Time::kNanosecondsPerMicrosecond);
780}
781
782// static
783constexpr TimeDelta TimeDelta::Max() {
784 return TimeDelta(std::numeric_limits<int64_t>::max());
785}
786
787// static
788constexpr TimeDelta TimeDelta::Min() {
789 return TimeDelta(std::numeric_limits<int64_t>::min());
790}
791
792// static
793constexpr TimeDelta TimeDelta::FromDouble(double value) {
794 // TODO(crbug.com/612601): Use saturated_cast<int64_t>(value) once we sort out
795 // the Min() behavior.
796 return value > std::numeric_limits<int64_t>::max()
797 ? Max()
798 : value < std::numeric_limits<int64_t>::min()
799 ? Min()
800 : TimeDelta(static_cast<int64_t>(value));
801}
802
803// static
804constexpr TimeDelta TimeDelta::FromProduct(int64_t value,
805 int64_t positive_value) {
806// DCHECK(positive_value > 0); // NOLINT, DCHECK_GT isn't constexpr.
807 return value > std::numeric_limits<int64_t>::max() / positive_value
808 ? Max()
809 : value < std::numeric_limits<int64_t>::min() / positive_value
810 ? Min()
811 : TimeDelta(value * positive_value);
812}
813
814// For logging use only.
815BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
816
817// TimeTicks ------------------------------------------------------------------
818
819// Represents monotonically non-decreasing clock time.
820class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> {
821 public:
822 // The underlying clock used to generate new TimeTicks.
823 enum class Clock {
824 FUCHSIA_ZX_CLOCK_MONOTONIC,
825 LINUX_CLOCK_MONOTONIC,
826 IOS_CF_ABSOLUTE_TIME_MINUS_KERN_BOOTTIME,
827 MAC_MACH_ABSOLUTE_TIME,
828 WIN_QPC,
829 WIN_ROLLOVER_PROTECTED_TIME_GET_TIME
830 };
831
832 constexpr TimeTicks() : TimeBase(0) {}
833
834 // Platform-dependent tick count representing "right now." When
835 // IsHighResolution() returns false, the resolution of the clock could be
836 // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
837 // microsecond.
838 static TimeTicks Now();
839
840 // Returns true if the high resolution clock is working on this system and
841 // Now() will return high resolution values. Note that, on systems where the
842 // high resolution clock works but is deemed inefficient, the low resolution
843 // clock will be used instead.
844 static bool IsHighResolution() WARN_UNUSED_RESULT;
845
846 // Returns true if TimeTicks is consistent across processes, meaning that
847 // timestamps taken on different processes can be safely compared with one
848 // another. (Note that, even on platforms where this returns true, time values
849 // from different threads that are within one tick of each other must be
850 // considered to have an ambiguous ordering.)
851 static bool IsConsistentAcrossProcesses() WARN_UNUSED_RESULT;
852
853#if defined(OS_FUCHSIA)
854 // Converts between TimeTicks and an ZX_CLOCK_MONOTONIC zx_time_t value.
855 static TimeTicks FromZxTime(zx_time_t nanos_since_boot);
856 zx_time_t ToZxTime() const;
857#endif
858
859#if defined(OS_WIN)
860 // Translates an absolute QPC timestamp into a TimeTicks value. The returned
861 // value has the same origin as Now(). Do NOT attempt to use this if
862 // IsHighResolution() returns false.
863 static TimeTicks FromQPCValue(LONGLONG qpc_value);
864#endif
865
866#if defined(OS_MACOSX) && !defined(OS_IOS)
867 static TimeTicks FromMachAbsoluteTime(uint64_t mach_absolute_time);
868#endif // defined(OS_MACOSX) && !defined(OS_IOS)
869
870#if defined(OS_ANDROID) || defined(OS_CHROMEOS)
871 // Converts to TimeTicks the value obtained from SystemClock.uptimeMillis().
872 // Note: this convertion may be non-monotonic in relation to previously
873 // obtained TimeTicks::Now() values because of the truncation (to
874 // milliseconds) performed by uptimeMillis().
875 static TimeTicks FromUptimeMillis(int64_t uptime_millis_value);
876#endif
877
878 // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because
879 // Time and TimeTicks respond differently to user-set time and NTP
880 // adjustments, this number is only an estimate. Nevertheless, this can be
881 // useful when you need to relate the value of TimeTicks to a real time and
882 // date. Note: Upon first invocation, this function takes a snapshot of the
883 // realtime clock to establish a reference point. This function will return
884 // the same value for the duration of the application, but will be different
885 // in future application runs.
886 static TimeTicks UnixEpoch();
887
888 // Returns |this| snapped to the next tick, given a |tick_phase| and
889 // repeating |tick_interval| in both directions. |this| may be before,
890 // after, or equal to the |tick_phase|.
891 TimeTicks SnappedToNextTick(TimeTicks tick_phase,
892 TimeDelta tick_interval) const;
893
894 // Returns an enum indicating the underlying clock being used to generate
895 // TimeTicks timestamps. This function should only be used for debugging and
896 // logging purposes.
897 static Clock GetClock();
898
899 // Converts an integer value representing TimeTicks to a class. This may be
900 // used when deserializing a |TimeTicks| structure, using a value known to be
901 // compatible. It is not provided as a constructor because the integer type
902 // may be unclear from the perspective of a caller.
903 //
904 // DEPRECATED - Do not use in new code. For deserializing TimeTicks values,
905 // prefer TimeTicks + TimeDelta(). http://crbug.com/634507
906 static constexpr TimeTicks FromInternalValue(int64_t us) {
907 return TimeTicks(us);
908 }
909
910 protected:
911#if defined(OS_WIN)
912 typedef DWORD (*TickFunctionType)(void);
913 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
914#endif
915
916 private:
917 friend class time_internal::TimeBase<TimeTicks>;
918
919 // Please use Now() to create a new object. This is for internal use
920 // and testing.
921 constexpr explicit TimeTicks(int64_t us) : TimeBase(us) {}
922};
923
924// For logging use only.
925BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
926
927// ThreadTicks ----------------------------------------------------------------
928
929// Represents a clock, specific to a particular thread, than runs only while the
930// thread is running.
931class BASE_EXPORT ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
932 public:
933 constexpr ThreadTicks() : TimeBase(0) {}
934
935 // Returns true if ThreadTicks::Now() is supported on this system.
936 static bool IsSupported() WARN_UNUSED_RESULT {
937#if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
938 (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID) || \
939 defined(OS_FUCHSIA)
940 return true;
941#elif defined(OS_WIN)
942 return IsSupportedWin();
943#else
944 return false;
945#endif
946 }
947
948 // Waits until the initialization is completed. Needs to be guarded with a
949 // call to IsSupported().
950 static void WaitUntilInitialized() {
951#if defined(OS_WIN)
952 WaitUntilInitializedWin();
953#endif
954 }
955
956 // Returns thread-specific CPU-time on systems that support this feature.
957 // Needs to be guarded with a call to IsSupported(). Use this timer
958 // to (approximately) measure how much time the calling thread spent doing
959 // actual work vs. being de-scheduled. May return bogus results if the thread
960 // migrates to another CPU between two calls. Returns an empty ThreadTicks
961 // object until the initialization is completed. If a clock reading is
962 // absolutely needed, call WaitUntilInitialized() before this method.
963 static ThreadTicks Now();
964
965#if defined(OS_WIN)
966 // Similar to Now() above except this returns thread-specific CPU time for an
967 // arbitrary thread. All comments for Now() method above apply apply to this
968 // method as well.
969 static ThreadTicks GetForThread(const PlatformThreadHandle& thread_handle);
970#endif
971
972 // Converts an integer value representing ThreadTicks to a class. This may be
973 // used when deserializing a |ThreadTicks| structure, using a value known to
974 // be compatible. It is not provided as a constructor because the integer type
975 // may be unclear from the perspective of a caller.
976 //
977 // DEPRECATED - Do not use in new code. For deserializing ThreadTicks values,
978 // prefer ThreadTicks + TimeDelta(). http://crbug.com/634507
979 static constexpr ThreadTicks FromInternalValue(int64_t us) {
980 return ThreadTicks(us);
981 }
982
983 private:
984 friend class time_internal::TimeBase<ThreadTicks>;
985
986 // Please use Now() or GetForThread() to create a new object. This is for
987 // internal use and testing.
988 constexpr explicit ThreadTicks(int64_t us) : TimeBase(us) {}
989
990#if defined(OS_WIN)
991 FRIEND_TEST_ALL_PREFIXES(TimeTicks, TSCTicksPerSecond);
992
993 // Returns the frequency of the TSC in ticks per second, or 0 if it hasn't
994 // been measured yet. Needs to be guarded with a call to IsSupported().
995 // This method is declared here rather than in the anonymous namespace to
996 // allow testing.
997 static double TSCTicksPerSecond();
998
999 static bool IsSupportedWin() WARN_UNUSED_RESULT;
1000 static void WaitUntilInitializedWin();
1001#endif
1002};
1003
1004// For logging use only.
1005BASE_EXPORT std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
1006
1007} // namespace base
1008
1009#endif // BASE_TIME_TIME_H_
1010