1 // Copyright 2012 The Chromium Authors
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
17 // time 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
20 // that `TimeTicks` may "stand still" (e.g., if the computer is suspended), and
21 // `ThreadTicks` will "stand still" whenever the thread has been de-scheduled
22 // by the operating system.
23 //
24 // All time classes are copyable, assignable, and occupy 64 bits per instance.
25 // Prefer to pass them by value, e.g.:
26 //
27 // void MyFunction(TimeDelta arg);
28 //
29 // All time classes support `operator<<` with logging streams, e.g. `LOG(INFO)`.
30 // For human-readable formatting, use //base/i18n/time_formatting.h.
31 //
32 // Example use cases for different time classes:
33 //
34 // Time: Interpreting the wall-clock time provided by a remote system.
35 // Detecting whether cached resources have expired. Providing the
36 // user with a display of the current date and time. Determining
37 // the amount of time between events across re-boots of the
38 // machine.
39 //
40 // TimeTicks: Tracking the amount of time a task runs. Executing delayed
41 // tasks at the right time. Computing presentation timestamps.
42 // Synchronizing audio and video using TimeTicks as a common
43 // reference clock (lip-sync). Measuring network round-trip
44 // latency.
45 //
46 // ThreadTicks: Benchmarking how long the current thread has been doing actual
47 // work.
48 //
49 // Serialization:
50 //
51 // Use the helpers in //base/json/values_util.h when serializing `Time`
52 // or `TimeDelta` to/from `base::Value`.
53 //
54 // Otherwise:
55 //
56 // - Time: use `FromDeltaSinceWindowsEpoch()`/`ToDeltaSinceWindowsEpoch()`.
57 // - TimeDelta: use `base::Microseconds()`/`InMicroseconds()`.
58 //
59 // `TimeTicks` and `ThreadTicks` do not have a stable origin; serialization for
60 // the purpose of persistence is not supported.
61
62 #ifndef BASE_TIME_TIME_H_
63 #define BASE_TIME_TIME_H_
64
65 #include <stdint.h>
66 #include <time.h>
67
68 #include <compare>
69 #include <iosfwd>
70 #include <limits>
71 #include <ostream>
72 #include <type_traits>
73
74 #include "base/base_export.h"
75 #include "base/check.h"
76 #include "base/check_op.h"
77 #include "base/compiler_specific.h"
78 #include "base/numerics/clamped_math.h"
79 #include "build/build_config.h"
80 #include "build/chromeos_buildflags.h"
81
82 #if BUILDFLAG(IS_FUCHSIA)
83 #include <zircon/types.h>
84 #endif
85
86 #if BUILDFLAG(IS_APPLE)
87 #include <CoreFoundation/CoreFoundation.h>
88 #include <mach/mach_time.h>
89 // Avoid Mac system header macro leak.
90 #undef TYPE_BOOL
91 #endif
92
93 #if BUILDFLAG(IS_ANDROID)
94 #include <jni.h>
95 #endif
96
97 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
98 #include <unistd.h>
99 #include <sys/time.h>
100 #endif
101
102 #if BUILDFLAG(IS_WIN)
103 #include "base/gtest_prod_util.h"
104 #include "base/win/windows_types.h"
105
106 namespace ABI {
107 namespace Windows {
108 namespace Foundation {
109 struct DateTime;
110 struct TimeSpan;
111 } // namespace Foundation
112 } // namespace Windows
113 } // namespace ABI
114 #endif
115
116 namespace base {
117
118 class PlatformThreadHandle;
119 class TimeDelta;
120
121 template <typename T>
122 constexpr TimeDelta Microseconds(T n);
123
124 namespace {
125
126 // TODO: Replace usage of this with std::isnan() once Chromium uses C++23,
127 // where that is constexpr.
isnan(double d)128 constexpr bool isnan(double d) {
129 return d != d;
130 }
131
132 }
133
134 // TimeDelta ------------------------------------------------------------------
135
136 class BASE_EXPORT TimeDelta {
137 public:
138 constexpr TimeDelta() = default;
139
140 #if BUILDFLAG(IS_WIN)
141 static TimeDelta FromQPCValue(LONGLONG qpc_value);
142 // TODO(crbug.com/989694): Avoid base::TimeDelta factory functions
143 // based on absolute time
144 static TimeDelta FromFileTime(FILETIME ft);
145 static TimeDelta FromWinrtDateTime(ABI::Windows::Foundation::DateTime dt);
146 static TimeDelta FromWinrtTimeSpan(ABI::Windows::Foundation::TimeSpan ts);
147 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
148 static TimeDelta FromTimeSpec(const timespec& ts);
149 #endif
150 #if BUILDFLAG(IS_FUCHSIA)
151 static TimeDelta FromZxDuration(zx_duration_t nanos);
152 #endif
153 #if BUILDFLAG(IS_APPLE)
154 static TimeDelta FromMachTime(uint64_t mach_time);
155 #endif // BUILDFLAG(IS_APPLE)
156
157 // Converts an integer value representing TimeDelta to a class. This is used
158 // when deserializing a |TimeDelta| structure, using a value known to be
159 // compatible. It is not provided as a constructor because the integer type
160 // may be unclear from the perspective of a caller.
161 //
162 // DEPRECATED - Do not use in new code. http://crbug.com/634507
FromInternalValue(int64_t delta)163 static constexpr TimeDelta FromInternalValue(int64_t delta) {
164 return TimeDelta(delta);
165 }
166
167 // Returns the maximum time delta, which should be greater than any reasonable
168 // time delta we might compare it to. If converted to double with ToDouble()
169 // it becomes an IEEE double infinity. Use FiniteMax() if you want a very
170 // large number that doesn't do this. TimeDelta math saturates at the end
171 // points so adding to TimeDelta::Max() leaves the value unchanged.
172 // Subtracting should leave the value unchanged but currently changes it
173 // TODO(https://crbug.com/869387).
174 static constexpr TimeDelta Max();
175
176 // Returns the minimum time delta, which should be less than than any
177 // reasonable time delta we might compare it to. For more details see the
178 // comments for Max().
179 static constexpr TimeDelta Min();
180
181 // Returns the maximum time delta which is not equivalent to infinity. Only
182 // subtracting a finite time delta from this time delta has a defined result.
183 static constexpr TimeDelta FiniteMax();
184
185 // Returns the minimum time delta which is not equivalent to -infinity. Only
186 // adding a finite time delta to this time delta has a defined result.
187 static constexpr TimeDelta FiniteMin();
188
189 // Returns the internal numeric value of the TimeDelta object. Please don't
190 // use this and do arithmetic on it, as it is more error prone than using the
191 // provided operators.
192 // For serializing, use FromInternalValue to reconstitute.
193 //
194 // DEPRECATED - Do not use in new code. http://crbug.com/634507
ToInternalValue()195 constexpr int64_t ToInternalValue() const { return delta_; }
196
197 // Returns the magnitude (absolute value) of this TimeDelta.
magnitude()198 constexpr TimeDelta magnitude() const { return TimeDelta(delta_.Abs()); }
199
200 // Returns true if the time delta is a zero, positive or negative time delta.
is_zero()201 constexpr bool is_zero() const { return delta_ == 0; }
is_positive()202 constexpr bool is_positive() const { return delta_ > 0; }
is_negative()203 constexpr bool is_negative() const { return delta_ < 0; }
204
205 // Returns true if the time delta is the maximum/minimum time delta.
is_max()206 constexpr bool is_max() const { return *this == Max(); }
is_min()207 constexpr bool is_min() const { return *this == Min(); }
is_inf()208 constexpr bool is_inf() const { return is_min() || is_max(); }
209
210 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
211 struct timespec ToTimeSpec() const;
212 #endif
213 #if BUILDFLAG(IS_FUCHSIA)
214 zx_duration_t ToZxDuration() const;
215 #endif
216 #if BUILDFLAG(IS_WIN)
217 ABI::Windows::Foundation::DateTime ToWinrtDateTime() const;
218 ABI::Windows::Foundation::TimeSpan ToWinrtTimeSpan() const;
219 #endif
220
221 // Returns the frequency in Hertz (cycles per second) that has a period of
222 // *this.
223 constexpr double ToHz() const;
224
225 // Returns the time delta in some unit. Minimum argument values return as
226 // -inf for doubles and min type values otherwise. Maximum ones are treated as
227 // +inf for doubles and max type values otherwise. Their results will produce
228 // an is_min() or is_max() TimeDelta. The InXYZF versions return a floating
229 // point value. The InXYZ versions return a truncated value (aka rounded
230 // towards zero, std::trunc() behavior). The InXYZFloored() versions round to
231 // lesser integers (std::floor() behavior). The XYZRoundedUp() versions round
232 // up to greater integers (std::ceil() behavior). WARNING: Floating point
233 // arithmetic is such that XXX(t.InXXXF()) may not precisely equal |t|.
234 // Hence, floating point values should not be used for storage.
235 constexpr int InDays() const;
236 constexpr int InDaysFloored() const;
237 constexpr int InHours() const;
238 constexpr int InMinutes() const;
239 constexpr double InSecondsF() const;
240 constexpr int64_t InSeconds() const;
241 constexpr int64_t InSecondsFloored() const;
242 constexpr double InMillisecondsF() const;
243 constexpr int64_t InMilliseconds() const;
244 constexpr int64_t InMillisecondsRoundedUp() const;
InMicroseconds()245 constexpr int64_t InMicroseconds() const { return delta_; }
246 constexpr double InMicrosecondsF() const;
247 constexpr int64_t InNanoseconds() const;
248
249 // Computations with other deltas.
250 constexpr TimeDelta operator+(TimeDelta other) const;
251 constexpr TimeDelta operator-(TimeDelta other) const;
252
253 constexpr TimeDelta& operator+=(TimeDelta other) {
254 return *this = (*this + other);
255 }
256 constexpr TimeDelta& operator-=(TimeDelta other) {
257 return *this = (*this - other);
258 }
259 constexpr TimeDelta operator-() const {
260 if (!is_inf())
261 return TimeDelta(-delta_);
262 return (delta_ < 0) ? Max() : Min();
263 }
264
265 // Computations with numeric types.
266 template <typename T>
267 constexpr TimeDelta operator*(T a) const {
268 return TimeDelta(int64_t{delta_ * a});
269 }
270 template <typename T>
271 constexpr TimeDelta operator/(T a) const {
272 return TimeDelta(int64_t{delta_ / a});
273 }
274 template <typename T>
275 constexpr TimeDelta& operator*=(T a) {
276 return *this = (*this * a);
277 }
278 template <typename T>
279 constexpr TimeDelta& operator/=(T a) {
280 return *this = (*this / a);
281 }
282
283 // This does floating-point division. For an integer result, either call
284 // IntDiv(), or (possibly clearer) use this operator with
285 // base::Clamp{Ceil,Floor,Round}() or base::saturated_cast() (for truncation).
286 // Note that converting to double here drops precision to 53 bits.
287 constexpr double operator/(TimeDelta a) const {
288 // 0/0 and inf/inf (any combination of positive and negative) are invalid
289 // (they are almost certainly not intentional, and result in NaN, which
290 // turns into 0 if clamped to an integer; this makes introducing subtle bugs
291 // too easy).
292 CHECK(!is_zero() || !a.is_zero());
293 CHECK(!is_inf() || !a.is_inf());
294
295 return ToDouble() / a.ToDouble();
296 }
IntDiv(TimeDelta a)297 constexpr int64_t IntDiv(TimeDelta a) const {
298 if (!is_inf() && !a.is_zero())
299 return int64_t{delta_ / a.delta_};
300
301 // For consistency, use the same edge case CHECKs and behavior as the code
302 // above.
303 CHECK(!is_zero() || !a.is_zero());
304 CHECK(!is_inf() || !a.is_inf());
305 return ((delta_ < 0) == (a.delta_ < 0))
306 ? std::numeric_limits<int64_t>::max()
307 : std::numeric_limits<int64_t>::min();
308 }
309
310 constexpr TimeDelta operator%(TimeDelta a) const {
311 return TimeDelta(
312 (is_inf() || a.is_zero() || a.is_inf()) ? delta_ : (delta_ % a.delta_));
313 }
314 constexpr TimeDelta& operator%=(TimeDelta other) {
315 return *this = (*this % other);
316 }
317
318 // Comparison operators.
319 friend constexpr bool operator==(TimeDelta, TimeDelta) = default;
320 friend constexpr std::strong_ordering operator<=>(TimeDelta,
321 TimeDelta) = default;
322
323 // Returns this delta, ceiled/floored/rounded-away-from-zero to the nearest
324 // multiple of |interval|.
325 TimeDelta CeilToMultiple(TimeDelta interval) const;
326 TimeDelta FloorToMultiple(TimeDelta interval) const;
327 TimeDelta RoundToMultiple(TimeDelta interval) const;
328
329 private:
330 // Constructs a delta given the duration in microseconds. This is private
331 // to avoid confusion by callers with an integer constructor. Use
332 // base::Seconds, base::Milliseconds, etc. instead.
TimeDelta(int64_t delta_us)333 constexpr explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {}
TimeDelta(ClampedNumeric<int64_t> delta_us)334 constexpr explicit TimeDelta(ClampedNumeric<int64_t> delta_us)
335 : delta_(delta_us) {}
336
337 // Returns a double representation of this TimeDelta's tick count. In
338 // particular, Max()/Min() are converted to +/-infinity.
ToDouble()339 constexpr double ToDouble() const {
340 if (!is_inf())
341 return static_cast<double>(delta_);
342 return (delta_ < 0) ? -std::numeric_limits<double>::infinity()
343 : std::numeric_limits<double>::infinity();
344 }
345
346 // Delta in microseconds.
347 ClampedNumeric<int64_t> delta_ = 0;
348 };
349
350 constexpr TimeDelta TimeDelta::operator+(TimeDelta other) const {
351 if (!other.is_inf())
352 return TimeDelta(delta_ + other.delta_);
353
354 // Additions involving two infinities are only valid if signs match.
355 CHECK(!is_inf() || (delta_ == other.delta_));
356 return other;
357 }
358
359 constexpr TimeDelta TimeDelta::operator-(TimeDelta other) const {
360 if (!other.is_inf())
361 return TimeDelta(delta_ - other.delta_);
362
363 // Subtractions involving two infinities are only valid if signs differ.
364 CHECK_NE(int64_t{delta_}, int64_t{other.delta_});
365 return (other.delta_ < 0) ? Max() : Min();
366 }
367
368 template <typename T>
369 constexpr TimeDelta operator*(T a, TimeDelta td) {
370 return td * a;
371 }
372
373 // For logging use only.
374 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
375
376 // TimeBase--------------------------------------------------------------------
377
378 // Do not reference the time_internal::TimeBase template class directly. Please
379 // use one of the time subclasses instead, and only reference the public
380 // TimeBase members via those classes.
381 namespace time_internal {
382
383 // Provides value storage and comparison/math operations common to all time
384 // classes. Each subclass provides for strong type-checking to ensure
385 // semantically meaningful comparison/math of time values from the same clock
386 // source or timeline.
387 template<class TimeClass>
388 class TimeBase {
389 public:
390 static constexpr int64_t kHoursPerDay = 24;
391 static constexpr int64_t kSecondsPerMinute = 60;
392 static constexpr int64_t kMinutesPerHour = 60;
393 static constexpr int64_t kSecondsPerHour =
394 kSecondsPerMinute * kMinutesPerHour;
395 static constexpr int64_t kMillisecondsPerSecond = 1000;
396 static constexpr int64_t kMillisecondsPerDay =
397 kMillisecondsPerSecond * kSecondsPerHour * kHoursPerDay;
398 static constexpr int64_t kMicrosecondsPerMillisecond = 1000;
399 static constexpr int64_t kMicrosecondsPerSecond =
400 kMicrosecondsPerMillisecond * kMillisecondsPerSecond;
401 static constexpr int64_t kMicrosecondsPerMinute =
402 kMicrosecondsPerSecond * kSecondsPerMinute;
403 static constexpr int64_t kMicrosecondsPerHour =
404 kMicrosecondsPerMinute * kMinutesPerHour;
405 static constexpr int64_t kMicrosecondsPerDay =
406 kMicrosecondsPerHour * kHoursPerDay;
407 static constexpr int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
408 static constexpr int64_t kNanosecondsPerMicrosecond = 1000;
409 static constexpr int64_t kNanosecondsPerSecond =
410 kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
411
412 // TODO(https://crbug.com/1392437): Remove concept of "null" from base::Time.
413 //
414 // Warning: Be careful when writing code that performs math on time values,
415 // since it's possible to produce a valid "zero" result that should not be
416 // interpreted as a "null" value. If you find yourself using this method or
417 // the zero-arg default constructor, please consider using an optional to
418 // express the null state.
419 //
420 // Returns true if this object has not been initialized (probably).
is_null()421 constexpr bool is_null() const { return us_ == 0; }
422
423 // Returns true if this object represents the maximum/minimum time.
is_max()424 constexpr bool is_max() const { return *this == Max(); }
is_min()425 constexpr bool is_min() const { return *this == Min(); }
is_inf()426 constexpr bool is_inf() const { return is_min() || is_max(); }
427
428 // Returns the maximum/minimum times, which should be greater/less than than
429 // any reasonable time with which we might compare it.
Max()430 static constexpr TimeClass Max() {
431 return TimeClass(std::numeric_limits<int64_t>::max());
432 }
433
Min()434 static constexpr TimeClass Min() {
435 return TimeClass(std::numeric_limits<int64_t>::min());
436 }
437
438 // For legacy serialization only. When serializing to `base::Value`, prefer
439 // the helpers from //base/json/values_util.h instead. Otherwise, use
440 // `Time::ToDeltaSinceWindowsEpoch()` for `Time` and
441 // `TimeDelta::InMicroseconds()` for `TimeDelta`. See http://crbug.com/634507.
ToInternalValue()442 constexpr int64_t ToInternalValue() const { return us_; }
443
444 // The amount of time since the origin (or "zero") point. This is a syntactic
445 // convenience to aid in code readability, mainly for debugging/testing use
446 // cases.
447 //
448 // Warning: While the Time subclass has a fixed origin point, the origin for
449 // the other subclasses can vary each time the application is restarted.
450 constexpr TimeDelta since_origin() const;
451
452 // Compute the difference between two times.
453 #if !defined(__aarch64__) && BUILDFLAG(IS_ANDROID)
454 NOINLINE // https://crbug.com/1369775
455 #endif
456 constexpr TimeDelta operator-(const TimeBase<TimeClass>& other) const;
457
458 // Return a new time modified by some delta.
459 constexpr TimeClass operator+(TimeDelta delta) const;
460 constexpr TimeClass operator-(TimeDelta delta) const;
461
462 // Modify by some time delta.
463 constexpr TimeClass& operator+=(TimeDelta delta) {
464 return static_cast<TimeClass&>(*this = (*this + delta));
465 }
466 constexpr TimeClass& operator-=(TimeDelta delta) {
467 return static_cast<TimeClass&>(*this = (*this - delta));
468 }
469
470 // Comparison operators
471 friend constexpr bool operator==(const TimeBase&, const TimeBase&) = default;
472 friend constexpr std::strong_ordering operator<=>(const TimeBase&,
473 const TimeBase&) = default;
474
475 protected:
TimeBase(int64_t us)476 constexpr explicit TimeBase(int64_t us) : us_(us) {}
477
478 // Time value in a microsecond timebase.
479 ClampedNumeric<int64_t> us_;
480 };
481
482 #if BUILDFLAG(IS_WIN)
483 #if defined(ARCH_CPU_ARM64)
484 // TSCTicksPerSecond is not supported on Windows on Arm systems because the
485 // cycle-counting methods use the actual CPU cycle count, and not a consistent
486 // incrementing counter.
487 #else
488 // Returns true if the CPU support constant rate TSC.
489 [[nodiscard]] BASE_EXPORT bool HasConstantRateTSC();
490
491 // Returns the frequency of the TSC in ticks per second, or 0 if it hasn't
492 // been measured yet. Needs to be guarded with a call to HasConstantRateTSC().
493 [[nodiscard]] BASE_EXPORT double TSCTicksPerSecond();
494 #endif
495 #endif // BUILDFLAG(IS_WIN)
496
497 } // namespace time_internal
498
499 template <class TimeClass>
500 inline constexpr TimeClass operator+(TimeDelta delta, TimeClass t) {
501 return t + delta;
502 }
503
504 // Time -----------------------------------------------------------------------
505
506 // Represents a wall clock time in UTC. Values are not guaranteed to be
507 // monotonically non-decreasing and are subject to large amounts of skew.
508 // Time is stored internally as microseconds since the Windows epoch (1601).
509 class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
510 public:
511 // Offset of UNIX epoch (1970-01-01 00:00:00 UTC) from Windows FILETIME epoch
512 // (1601-01-01 00:00:00 UTC), in microseconds. This value is derived from the
513 // following: ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the number
514 // of leap year days between 1601 and 1970: (1970-1601)/4 excluding 1700,
515 // 1800, and 1900.
516 static constexpr int64_t kTimeTToMicrosecondsOffset =
517 INT64_C(11644473600000000);
518
519 #if BUILDFLAG(IS_WIN)
520 // To avoid overflow in QPC to Microseconds calculations, since we multiply
521 // by kMicrosecondsPerSecond, then the QPC value should not exceed
522 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
523 static constexpr int64_t kQPCOverflowThreshold = INT64_C(0x8637BD05AF7);
524 #endif
525
526 // kExplodedMinYear and kExplodedMaxYear define the platform-specific limits
527 // for values passed to FromUTCExploded() and FromLocalExploded(). Those
528 // functions will return false if passed values outside these limits. The limits
529 // are inclusive, meaning that the API should support all dates within a given
530 // limit year.
531 //
532 // WARNING: These are not the same limits for the inverse functionality,
533 // UTCExplode() and LocalExplode(). See method comments for further details.
534 #if BUILDFLAG(IS_WIN)
535 static constexpr int kExplodedMinYear = 1601;
536 static constexpr int kExplodedMaxYear = 30827;
537 #elif BUILDFLAG(IS_IOS) && !__LP64__
538 static constexpr int kExplodedMinYear = std::numeric_limits<int>::min();
539 static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
540 #elif BUILDFLAG(IS_APPLE)
541 static constexpr int kExplodedMinYear = 1902;
542 static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
543 #elif BUILDFLAG(IS_ANDROID)
544 // Though we use 64-bit time APIs on both 32 and 64 bit Android, some OS
545 // versions like KitKat (ARM but not x86 emulator) can't handle some early
546 // dates (e.g. before 1170). So we set min conservatively here.
547 static constexpr int kExplodedMinYear = 1902;
548 static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
549 #else
550 static constexpr int kExplodedMinYear =
551 (sizeof(time_t) == 4 ? 1902 : std::numeric_limits<int>::min());
552 static constexpr int kExplodedMaxYear =
553 (sizeof(time_t) == 4 ? 2037 : std::numeric_limits<int>::max());
554 #endif
555
556 // Represents an exploded time. This is kind of like the Win32 SYSTEMTIME
557 // structure or the Unix "struct tm" with a few additions and changes to
558 // prevent errors.
559 //
560 // This structure always represents dates in the Gregorian calendar and always
561 // encodes day_of_week as Sunday==0, Monday==1, .., Saturday==6. This means
562 // that base::Time::LocalExplode and base::Time::FromLocalExploded only
563 // respect the current local time zone in the conversion and do *not* use a
564 // calendar or day-of-week encoding from the current locale.
565 //
566 // NOTE: Generally, you should prefer the functions in
567 // base/i18n/time_formatting.h (in particular,
568 // `UnlocalizedTimeFormatWithPattern()`) over trying to create a formatted
569 // time string from this object.
570 struct BASE_EXPORT Exploded {
571 int year; // Four digit year "2007"
572 int month; // 1-based month (values 1 = January, etc.)
573 int day_of_week; // 0-based day of week (0 = Sunday, etc.)
574 int day_of_month; // 1-based day of month (1-31)
575 int hour; // Hour within the current day (0-23)
576 int minute; // Minute within the current hour (0-59)
577 int second; // Second within the current minute (0-59 plus leap
578 // seconds which may take it up to 60).
579 int millisecond; // Milliseconds within the current second (0-999)
580
581 // A cursory test for whether the data members are within their
582 // respective ranges. A 'true' return value does not guarantee the
583 // Exploded value can be successfully converted to a Time value.
584 bool HasValidValues() const;
585 };
586
587 // TODO(https://crbug.com/1392437): Remove concept of "null" from base::Time.
588 //
589 // Warning: Be careful when writing code that performs math on time values,
590 // since it's possible to produce a valid "zero" result that should not be
591 // interpreted as a "null" value. If you find yourself using this constructor
592 // or the is_null() method, please consider using an optional to express the
593 // null state.
594 //
595 // Contains the NULL time. Use Time::Now() to get the current time.
Time()596 constexpr Time() : TimeBase(0) {}
597
598 // Returns the time for epoch in Unix-like system (Jan 1, 1970).
UnixEpoch()599 static constexpr Time UnixEpoch() { return Time(kTimeTToMicrosecondsOffset); }
600
601 // Returns the current time. Watch out, the system might adjust its clock
602 // in which case time will actually go backwards. We don't guarantee that
603 // times are increasing, or that two calls to Now() won't be the same.
604 static Time Now();
605
606 // Returns the current time. Same as Now() except that this function always
607 // uses system time so that there are no discrepancies between the returned
608 // time and system time even on virtual environments including our test bot.
609 // For timing sensitive unittests, this function should be used.
610 static Time NowFromSystemTime();
611
612 // Converts to/from TimeDeltas relative to the Windows epoch (1601-01-01
613 // 00:00:00 UTC).
614 //
615 // For serialization, when handling `base::Value`, prefer the helpers in
616 // //base/json/values_util.h instead. Otherwise, use these methods for
617 // opaque serialization and deserialization, e.g.
618 //
619 // // Serialization:
620 // base::Time last_updated = ...;
621 // SaveToDatabase(last_updated.ToDeltaSinceWindowsEpoch().InMicroseconds());
622 //
623 // // Deserialization:
624 // base::Time last_updated = base::Time::FromDeltaSinceWindowsEpoch(
625 // base::Microseconds(LoadFromDatabase()));
626 //
627 // Do not use `FromInternalValue()` or `ToInternalValue()` for this purpose.
FromDeltaSinceWindowsEpoch(TimeDelta delta)628 static constexpr Time FromDeltaSinceWindowsEpoch(TimeDelta delta) {
629 return Time(delta.InMicroseconds());
630 }
631
ToDeltaSinceWindowsEpoch()632 constexpr TimeDelta ToDeltaSinceWindowsEpoch() const {
633 return Microseconds(us_);
634 }
635
636 // Converts to/from time_t in UTC and a Time class.
637 static constexpr Time FromTimeT(time_t tt);
638 constexpr time_t ToTimeT() const;
639
640 // Converts time to/from a number of seconds since the Unix epoch (Jan 1,
641 // 1970).
642 //
643 // TODO(crbug.com/1495550): Add integral versions and use them.
644 // TODO(crbug.com/1495554): Add ...PreservingNull() versions; see comments in
645 // the implementation of FromSecondsSinceUnixEpoch().
646 static constexpr Time FromSecondsSinceUnixEpoch(double dt);
647 constexpr double InSecondsFSinceUnixEpoch() const;
648
649 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
650 // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
651 // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
652 // having a 1 second resolution, which agrees with
653 // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
654 static constexpr Time FromTimeSpec(const timespec& ts);
655 #endif
656
657 // Converts to/from a number of milliseconds since the Unix epoch.
658 // TODO(crbug.com/1495554): Add ...PreservingNull() versions; see comments in
659 // the implementation of FromMillisecondsSinceUnixEpoch().
660 static constexpr Time FromMillisecondsSinceUnixEpoch(int64_t dt);
661 static constexpr Time FromMillisecondsSinceUnixEpoch(double dt);
662 // Explicitly forward calls with smaller integral types to the int64_t
663 // version; otherwise such calls would need to manually cast their args to
664 // int64_t, since the compiler isn't sure whether to promote to int64_t or
665 // double.
666 template <typename T,
667 typename = std::enable_if_t<
668 std::is_integral_v<T> && !std::is_same_v<T, int64_t> &&
669 (sizeof(T) < sizeof(int64_t) ||
670 (sizeof(T) == sizeof(int64_t) && std::is_signed_v<T>))>>
FromMillisecondsSinceUnixEpoch(T ms_since_epoch)671 static constexpr Time FromMillisecondsSinceUnixEpoch(T ms_since_epoch) {
672 return FromMillisecondsSinceUnixEpoch(int64_t{ms_since_epoch});
673 }
674 constexpr int64_t InMillisecondsSinceUnixEpoch() const;
675 // Don't use InMillisecondsFSinceUnixEpoch() in new code, since it contains a
676 // subtle hack (only exactly 1601-01-01 00:00 UTC is represented as 1970-01-01
677 // 00:00 UTC), and that is not appropriate for general use. Try to use
678 // InMillisecondsFSinceUnixEpochIgnoringNull() unless you have a very good
679 // reason to use InMillisecondsFSinceUnixEpoch().
680 //
681 // TODO(crbug.com/1495554): Rename the no-suffix version to
682 // "...PreservingNull()" and remove the suffix from the other version, to
683 // guide people to the preferable API.
684 constexpr double InMillisecondsFSinceUnixEpoch() const;
685 constexpr double InMillisecondsFSinceUnixEpochIgnoringNull() const;
686
687 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
688 static Time FromTimeVal(struct timeval t);
689 struct timeval ToTimeVal() const;
690 #endif
691
692 #if BUILDFLAG(IS_FUCHSIA)
693 static Time FromZxTime(zx_time_t time);
694 zx_time_t ToZxTime() const;
695 #endif
696
697 #if BUILDFLAG(IS_APPLE)
698 static Time FromCFAbsoluteTime(CFAbsoluteTime t);
699 CFAbsoluteTime ToCFAbsoluteTime() const;
700 #if defined(__OBJC__)
701 static Time FromNSDate(NSDate* date);
702 NSDate* ToNSDate() const;
703 #endif
704 #endif
705
706 #if BUILDFLAG(IS_WIN)
707 static Time FromFileTime(FILETIME ft);
708 FILETIME ToFileTime() const;
709
710 // The minimum time of a low resolution timer. This is basically a windows
711 // constant of ~15.6ms. While it does vary on some older OS versions, we'll
712 // treat it as static across all windows versions.
713 static const int kMinLowResolutionThresholdMs = 16;
714
715 // Enable or disable Windows high resolution timer.
716 static void EnableHighResolutionTimer(bool enable);
717
718 // Activates or deactivates the high resolution timer based on the |activate|
719 // flag. If the HighResolutionTimer is not Enabled (see
720 // EnableHighResolutionTimer), this function will return false. Otherwise
721 // returns true. Each successful activate call must be paired with a
722 // subsequent deactivate call.
723 // All callers to activate the high resolution timer must eventually call
724 // this function to deactivate the high resolution timer.
725 static bool ActivateHighResolutionTimer(bool activate);
726
727 // Returns true if the high resolution timer is both enabled and activated.
728 // This is provided for testing only, and is not tracked in a thread-safe
729 // way.
730 static bool IsHighResolutionTimerInUse();
731
732 // The following two functions are used to report the fraction of elapsed time
733 // that the high resolution timer is activated.
734 // ResetHighResolutionTimerUsage() resets the cumulative usage and starts the
735 // measurement interval and GetHighResolutionTimerUsage() returns the
736 // percentage of time since the reset that the high resolution timer was
737 // activated.
738 // ResetHighResolutionTimerUsage() must be called at least once before calling
739 // GetHighResolutionTimerUsage(); otherwise the usage result would be
740 // undefined.
741 static void ResetHighResolutionTimerUsage();
742 static double GetHighResolutionTimerUsage();
743 #endif // BUILDFLAG(IS_WIN)
744
745 // Converts an exploded structure representing either the local time or UTC
746 // into a Time class. Returns false on a failure when, for example, a day of
747 // month is set to 31 on a 28-30 day month. Returns Time(0) on overflow.
748 // FromLocalExploded respects the current time zone but does not attempt to
749 // use the calendar or day-of-week encoding from the current locale - see the
750 // comments on Exploded for more information.
FromUTCExploded(const Exploded & exploded,Time * time)751 [[nodiscard]] static bool FromUTCExploded(const Exploded& exploded,
752 Time* time) {
753 return FromExploded(false, exploded, time);
754 }
FromLocalExploded(const Exploded & exploded,Time * time)755 [[nodiscard]] static bool FromLocalExploded(const Exploded& exploded,
756 Time* time) {
757 return FromExploded(true, exploded, time);
758 }
759
760 // Converts a string representation of time to a Time object.
761 // An example of a time string which is converted is as below:-
762 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
763 // in the input string, FromString assumes local time and FromUTCString
764 // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
765 // specified in RFC822) is treated as if the timezone is not specified.
766 //
767 // WARNING: the underlying converter is very permissive. For example: it is
768 // not checked whether a given day of the week matches the date; Feb 29
769 // silently becomes Mar 1 in non-leap years; under certain conditions, whole
770 // English sentences may be parsed successfully and yield unexpected results.
771 //
772 // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
773 // a new time converter class.
FromString(const char * time_string,Time * parsed_time)774 [[nodiscard]] static bool FromString(const char* time_string,
775 Time* parsed_time) {
776 return FromStringInternal(time_string, true, parsed_time);
777 }
FromUTCString(const char * time_string,Time * parsed_time)778 [[nodiscard]] static bool FromUTCString(const char* time_string,
779 Time* parsed_time) {
780 return FromStringInternal(time_string, false, parsed_time);
781 }
782
783 // Fills the given |exploded| structure with either the local time or UTC from
784 // this Time instance. If the conversion cannot be made, the output will be
785 // assigned invalid values. Use Exploded::HasValidValues() to confirm a
786 // successful conversion.
787 //
788 // Y10K compliance: This method will successfully convert all Times that
789 // represent dates on/after the start of the year 1601 and on/before the start
790 // of the year 30828. Some platforms might convert over a wider input range.
791 // LocalExplode respects the current time zone but does not attempt to use the
792 // calendar or day-of-week encoding from the current locale - see the comments
793 // on Exploded for more information.
UTCExplode(Exploded * exploded)794 void UTCExplode(Exploded* exploded) const { Explode(false, exploded); }
LocalExplode(Exploded * exploded)795 void LocalExplode(Exploded* exploded) const { Explode(true, exploded); }
796
797 // The following two functions round down the time to the nearest day in
798 // either UTC or local time. It will represent midnight on that day.
UTCMidnight()799 Time UTCMidnight() const { return Midnight(false); }
LocalMidnight()800 Time LocalMidnight() const { return Midnight(true); }
801
802 // For legacy deserialization only. Converts an integer value representing
803 // Time to a class. This may be used when deserializing a |Time| structure,
804 // using a value known to be compatible. It is not provided as a constructor
805 // because the integer type may be unclear from the perspective of a caller.
806 //
807 // DEPRECATED - Do not use in new code. When deserializing from `base::Value`,
808 // prefer the helpers from //base/json/values_util.h instead.
809 // Otherwise, use `Time::FromDeltaSinceWindowsEpoch()` for `Time` and
810 // `Microseconds()` for `TimeDelta`. http://crbug.com/634507
FromInternalValue(int64_t us)811 static constexpr Time FromInternalValue(int64_t us) { return Time(us); }
812
813 private:
814 friend class time_internal::TimeBase<Time>;
815
Time(int64_t microseconds_since_win_epoch)816 constexpr explicit Time(int64_t microseconds_since_win_epoch)
817 : TimeBase(microseconds_since_win_epoch) {}
818
819 // Explodes the given time to either local time |is_local = true| or UTC
820 // |is_local = false|.
821 void Explode(bool is_local, Exploded* exploded) const;
822
823 // Unexplodes a given time assuming the source is either local time
824 // |is_local = true| or UTC |is_local = false|. Function returns false on
825 // failure and sets |time| to Time(0). Otherwise returns true and sets |time|
826 // to non-exploded time.
827 [[nodiscard]] static bool FromExploded(bool is_local,
828 const Exploded& exploded,
829 Time* time);
830
831 // Some platforms use the ICU library to provide To/FromExploded, when their
832 // native library implementations are insufficient in some way.
833 static void ExplodeUsingIcu(int64_t millis_since_unix_epoch,
834 bool is_local,
835 Exploded* exploded);
836 [[nodiscard]] static bool FromExplodedUsingIcu(
837 bool is_local,
838 const Exploded& exploded,
839 int64_t* millis_since_unix_epoch);
840
841 // Rounds down the time to the nearest day in either local time
842 // |is_local = true| or UTC |is_local = false|.
843 Time Midnight(bool is_local) const;
844
845 // Converts a string representation of time to a Time object.
846 // An example of a time string which is converted is as below:-
847 // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
848 // in the input string, local time |is_local = true| or
849 // UTC |is_local = false| is assumed. A timezone that cannot be parsed
850 // (e.g. "UTC" which is not specified in RFC822) is treated as if the
851 // timezone is not specified.
852 [[nodiscard]] static bool FromStringInternal(const char* time_string,
853 bool is_local,
854 Time* parsed_time);
855
856 // Comparison does not consider |day_of_week| when doing the operation.
857 [[nodiscard]] static bool ExplodedMostlyEquals(const Exploded& lhs,
858 const Exploded& rhs);
859
860 // Converts the provided time in milliseconds since the Unix epoch (1970) to a
861 // Time object, avoiding overflows.
862 [[nodiscard]] static bool FromMillisecondsSinceUnixEpoch(
863 int64_t unix_milliseconds,
864 Time* time);
865
866 // Returns the milliseconds since the Unix epoch (1970), rounding the
867 // microseconds towards -infinity.
868 int64_t ToRoundedDownMillisecondsSinceUnixEpoch() const;
869 };
870
871 // Factory methods that return a TimeDelta of the given unit.
872 // WARNING: Floating point arithmetic is such that XXX(t.InXXXF()) may not
873 // precisely equal |t|. Hence, floating point values should not be used for
874 // storage.
875
876 template <typename T>
Days(T n)877 constexpr TimeDelta Days(T n) {
878 return TimeDelta::FromInternalValue(MakeClampedNum(n) *
879 Time::kMicrosecondsPerDay);
880 }
881 template <typename T>
Hours(T n)882 constexpr TimeDelta Hours(T n) {
883 return TimeDelta::FromInternalValue(MakeClampedNum(n) *
884 Time::kMicrosecondsPerHour);
885 }
886 template <typename T>
Minutes(T n)887 constexpr TimeDelta Minutes(T n) {
888 return TimeDelta::FromInternalValue(MakeClampedNum(n) *
889 Time::kMicrosecondsPerMinute);
890 }
891 template <typename T>
Seconds(T n)892 constexpr TimeDelta Seconds(T n) {
893 return TimeDelta::FromInternalValue(MakeClampedNum(n) *
894 Time::kMicrosecondsPerSecond);
895 }
896 template <typename T>
Milliseconds(T n)897 constexpr TimeDelta Milliseconds(T n) {
898 return TimeDelta::FromInternalValue(MakeClampedNum(n) *
899 Time::kMicrosecondsPerMillisecond);
900 }
901 template <typename T>
Microseconds(T n)902 constexpr TimeDelta Microseconds(T n) {
903 return TimeDelta::FromInternalValue(MakeClampedNum(n));
904 }
905 template <typename T>
Nanoseconds(T n)906 constexpr TimeDelta Nanoseconds(T n) {
907 return TimeDelta::FromInternalValue(MakeClampedNum(n) /
908 Time::kNanosecondsPerMicrosecond);
909 }
910 template <typename T>
Hertz(T n)911 constexpr TimeDelta Hertz(T n) {
912 return n ? TimeDelta::FromInternalValue(Time::kMicrosecondsPerSecond /
913 MakeClampedNum(n))
914 : TimeDelta::Max();
915 }
916
917 // TimeDelta functions that must appear below the declarations of Time/TimeDelta
918
ToHz()919 constexpr double TimeDelta::ToHz() const {
920 return Seconds(1) / *this;
921 }
922
InDays()923 constexpr int TimeDelta::InDays() const {
924 if (!is_inf()) {
925 return static_cast<int>(delta_ / Time::kMicrosecondsPerDay);
926 }
927 return (delta_ < 0) ? std::numeric_limits<int>::min()
928 : std::numeric_limits<int>::max();
929 }
930
InDaysFloored()931 constexpr int TimeDelta::InDaysFloored() const {
932 if (!is_inf()) {
933 const int result = delta_ / Time::kMicrosecondsPerDay;
934 // Convert |result| from truncating to flooring.
935 return (result * Time::kMicrosecondsPerDay > delta_) ? (result - 1)
936 : result;
937 }
938 return (delta_ < 0) ? std::numeric_limits<int>::min()
939 : std::numeric_limits<int>::max();
940 }
941
InHours()942 constexpr int TimeDelta::InHours() const {
943 // saturated_cast<> is necessary since very large (but still less than
944 // min/max) deltas would result in overflow.
945 return saturated_cast<int>(delta_ / Time::kMicrosecondsPerHour);
946 }
947
InMinutes()948 constexpr int TimeDelta::InMinutes() const {
949 // saturated_cast<> is necessary since very large (but still less than
950 // min/max) deltas would result in overflow.
951 return saturated_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
952 }
953
InSecondsF()954 constexpr double TimeDelta::InSecondsF() const {
955 if (!is_inf())
956 return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond;
957 return (delta_ < 0) ? -std::numeric_limits<double>::infinity()
958 : std::numeric_limits<double>::infinity();
959 }
960
InSeconds()961 constexpr int64_t TimeDelta::InSeconds() const {
962 return is_inf() ? delta_ : (delta_ / Time::kMicrosecondsPerSecond);
963 }
964
InSecondsFloored()965 constexpr int64_t TimeDelta::InSecondsFloored() const {
966 if (!is_inf()) {
967 const int64_t result = delta_ / Time::kMicrosecondsPerSecond;
968 // Convert |result| from truncating to flooring.
969 return (result * Time::kMicrosecondsPerSecond > delta_) ? (result - 1)
970 : result;
971 }
972 return delta_;
973 }
974
InMillisecondsF()975 constexpr double TimeDelta::InMillisecondsF() const {
976 if (!is_inf()) {
977 return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond;
978 }
979 return (delta_ < 0) ? -std::numeric_limits<double>::infinity()
980 : std::numeric_limits<double>::infinity();
981 }
982
InMilliseconds()983 constexpr int64_t TimeDelta::InMilliseconds() const {
984 if (!is_inf()) {
985 return delta_ / Time::kMicrosecondsPerMillisecond;
986 }
987 return (delta_ < 0) ? std::numeric_limits<int64_t>::min()
988 : std::numeric_limits<int64_t>::max();
989 }
990
InMillisecondsRoundedUp()991 constexpr int64_t TimeDelta::InMillisecondsRoundedUp() const {
992 if (!is_inf()) {
993 const int64_t result = delta_ / Time::kMicrosecondsPerMillisecond;
994 // Convert |result| from truncating to ceiling.
995 return (delta_ > result * Time::kMicrosecondsPerMillisecond) ? (result + 1)
996 : result;
997 }
998 return delta_;
999 }
1000
InMicrosecondsF()1001 constexpr double TimeDelta::InMicrosecondsF() const {
1002 if (!is_inf()) {
1003 return static_cast<double>(delta_);
1004 }
1005 return (delta_ < 0) ? -std::numeric_limits<double>::infinity()
1006 : std::numeric_limits<double>::infinity();
1007 }
1008
InNanoseconds()1009 constexpr int64_t TimeDelta::InNanoseconds() const {
1010 return base::ClampMul(delta_, Time::kNanosecondsPerMicrosecond);
1011 }
1012
1013 // static
Max()1014 constexpr TimeDelta TimeDelta::Max() {
1015 return TimeDelta(std::numeric_limits<int64_t>::max());
1016 }
1017
1018 // static
Min()1019 constexpr TimeDelta TimeDelta::Min() {
1020 return TimeDelta(std::numeric_limits<int64_t>::min());
1021 }
1022
1023 // static
FiniteMax()1024 constexpr TimeDelta TimeDelta::FiniteMax() {
1025 return TimeDelta(std::numeric_limits<int64_t>::max() - 1);
1026 }
1027
1028 // static
FiniteMin()1029 constexpr TimeDelta TimeDelta::FiniteMin() {
1030 return TimeDelta(std::numeric_limits<int64_t>::min() + 1);
1031 }
1032
1033 // TimeBase functions that must appear below the declarations of Time/TimeDelta
1034 namespace time_internal {
1035
1036 template <class TimeClass>
since_origin()1037 constexpr TimeDelta TimeBase<TimeClass>::since_origin() const {
1038 return Microseconds(us_);
1039 }
1040
1041 template <class TimeClass>
1042 constexpr TimeDelta TimeBase<TimeClass>::operator-(
1043 const TimeBase<TimeClass>& other) const {
1044 return Microseconds(us_ - other.us_);
1045 }
1046
1047 template <class TimeClass>
1048 constexpr TimeClass TimeBase<TimeClass>::operator+(TimeDelta delta) const {
1049 return TimeClass((Microseconds(us_) + delta).InMicroseconds());
1050 }
1051
1052 template <class TimeClass>
1053 constexpr TimeClass TimeBase<TimeClass>::operator-(TimeDelta delta) const {
1054 return TimeClass((Microseconds(us_) - delta).InMicroseconds());
1055 }
1056
1057 } // namespace time_internal
1058
1059 // Time functions that must appear below the declarations of Time/TimeDelta
1060
1061 // static
FromTimeT(time_t tt)1062 constexpr Time Time::FromTimeT(time_t tt) {
1063 if (tt == 0)
1064 return Time(); // Preserve 0 so we can tell it doesn't exist.
1065 return (tt == std::numeric_limits<time_t>::max())
1066 ? Max()
1067 : (UnixEpoch() + Seconds(tt));
1068 }
1069
ToTimeT()1070 constexpr time_t Time::ToTimeT() const {
1071 if (is_null()) {
1072 return 0; // Preserve 0 so we can tell it doesn't exist.
1073 }
1074 if (!is_inf()) {
1075 return saturated_cast<time_t>((*this - UnixEpoch()).InSecondsFloored());
1076 }
1077 return (us_ < 0) ? std::numeric_limits<time_t>::min()
1078 : std::numeric_limits<time_t>::max();
1079 }
1080
1081 // static
FromSecondsSinceUnixEpoch(double dt)1082 constexpr Time Time::FromSecondsSinceUnixEpoch(double dt) {
1083 // Preserve 0.
1084 //
1085 // TODO(crbug.com/1495554): This is an unfortunate artifact of WebKit using 0
1086 // to mean "no time". Add a "...PreservingNull()" version that does this,
1087 // convert the minimum necessary set of callers to use it, and remove the zero
1088 // check here.
1089 return (dt == 0 || isnan(dt)) ? Time() : (UnixEpoch() + Seconds(dt));
1090 }
1091
InSecondsFSinceUnixEpoch()1092 constexpr double Time::InSecondsFSinceUnixEpoch() const {
1093 // Preserve 0.
1094 if (is_null()) {
1095 return 0;
1096 }
1097 if (!is_inf()) {
1098 return (*this - UnixEpoch()).InSecondsF();
1099 }
1100 return (us_ < 0) ? -std::numeric_limits<double>::infinity()
1101 : std::numeric_limits<double>::infinity();
1102 }
1103
1104 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
1105 // static
FromTimeSpec(const timespec & ts)1106 constexpr Time Time::FromTimeSpec(const timespec& ts) {
1107 return FromSecondsSinceUnixEpoch(ts.tv_sec + static_cast<double>(ts.tv_nsec) /
1108 kNanosecondsPerSecond);
1109 }
1110 #endif
1111
1112 // static
FromMillisecondsSinceUnixEpoch(int64_t dt)1113 constexpr Time Time::FromMillisecondsSinceUnixEpoch(int64_t dt) {
1114 // TODO(crbug.com/1495554): The lack of zero-preservation here doesn't match
1115 // InMillisecondsSinceUnixEpoch(), which is dangerous since it means
1116 // round-trips are not necessarily idempotent. Add "...PreservingNull()"
1117 // versions that explicitly check for zeros, convert the minimum necessary set
1118 // of callers to use them, and remove the null-check in
1119 // InMillisecondsSinceUnixEpoch().
1120 return UnixEpoch() + Milliseconds(dt);
1121 }
1122
1123 // static
FromMillisecondsSinceUnixEpoch(double dt)1124 constexpr Time Time::FromMillisecondsSinceUnixEpoch(double dt) {
1125 return isnan(dt) ? Time() : (UnixEpoch() + Milliseconds(dt));
1126 }
1127
InMillisecondsSinceUnixEpoch()1128 constexpr int64_t Time::InMillisecondsSinceUnixEpoch() const {
1129 // Preserve 0.
1130 if (is_null()) {
1131 return 0;
1132 }
1133 if (!is_inf()) {
1134 return (*this - UnixEpoch()).InMilliseconds();
1135 }
1136 return (us_ < 0) ? std::numeric_limits<int64_t>::min()
1137 : std::numeric_limits<int64_t>::max();
1138 }
1139
InMillisecondsFSinceUnixEpoch()1140 constexpr double Time::InMillisecondsFSinceUnixEpoch() const {
1141 // Preserve 0.
1142 return is_null() ? 0 : InMillisecondsFSinceUnixEpochIgnoringNull();
1143 }
1144
InMillisecondsFSinceUnixEpochIgnoringNull()1145 constexpr double Time::InMillisecondsFSinceUnixEpochIgnoringNull() const {
1146 // Preserve max and min without offset to prevent over/underflow.
1147 if (!is_inf()) {
1148 return (*this - UnixEpoch()).InMillisecondsF();
1149 }
1150 return (us_ < 0) ? -std::numeric_limits<double>::infinity()
1151 : std::numeric_limits<double>::infinity();
1152 }
1153
1154 // For logging use only.
1155 BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
1156
1157 // TimeTicks ------------------------------------------------------------------
1158
1159 // Represents monotonically non-decreasing clock time.
1160 class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> {
1161 public:
1162 // The underlying clock used to generate new TimeTicks.
1163 enum class Clock {
1164 FUCHSIA_ZX_CLOCK_MONOTONIC,
1165 LINUX_CLOCK_MONOTONIC,
1166 IOS_CF_ABSOLUTE_TIME_MINUS_KERN_BOOTTIME,
1167 MAC_MACH_ABSOLUTE_TIME,
1168 WIN_QPC,
1169 WIN_ROLLOVER_PROTECTED_TIME_GET_TIME
1170 };
1171
TimeTicks()1172 constexpr TimeTicks() : TimeBase(0) {}
1173
1174 // Platform-dependent tick count representing "right now." When
1175 // IsHighResolution() returns false, the resolution of the clock could be
1176 // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
1177 // microsecond.
1178 static TimeTicks Now();
1179
1180 // Returns true if the high resolution clock is working on this system and
1181 // Now() will return high resolution values. Note that, on systems where the
1182 // high resolution clock works but is deemed inefficient, the low resolution
1183 // clock will be used instead.
1184 [[nodiscard]] static bool IsHighResolution();
1185
1186 // Returns true if TimeTicks is consistent across processes, meaning that
1187 // timestamps taken on different processes can be safely compared with one
1188 // another. (Note that, even on platforms where this returns true, time values
1189 // from different threads that are within one tick of each other must be
1190 // considered to have an ambiguous ordering.)
1191 [[nodiscard]] static bool IsConsistentAcrossProcesses();
1192
1193 #if BUILDFLAG(IS_FUCHSIA)
1194 // Converts between TimeTicks and an ZX_CLOCK_MONOTONIC zx_time_t value.
1195 static TimeTicks FromZxTime(zx_time_t nanos_since_boot);
1196 zx_time_t ToZxTime() const;
1197 #endif
1198
1199 #if BUILDFLAG(IS_WIN)
1200 // Translates an absolute QPC timestamp into a TimeTicks value. The returned
1201 // value has the same origin as Now(). Do NOT attempt to use this if
1202 // IsHighResolution() returns false.
1203 static TimeTicks FromQPCValue(LONGLONG qpc_value);
1204 #endif
1205
1206 #if BUILDFLAG(IS_APPLE)
1207 static TimeTicks FromMachAbsoluteTime(uint64_t mach_absolute_time);
1208
1209 // Sets the current Mach timebase to `timebase`. Returns the old timebase.
1210 static mach_timebase_info_data_t SetMachTimebaseInfoForTesting(
1211 mach_timebase_info_data_t timebase);
1212
1213 #endif // BUILDFLAG(IS_APPLE)
1214
1215 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH)
1216 // Converts to TimeTicks the value obtained from SystemClock.uptimeMillis().
1217 // Note: this conversion may be non-monotonic in relation to previously
1218 // obtained TimeTicks::Now() values because of the truncation (to
1219 // milliseconds) performed by uptimeMillis().
1220 static TimeTicks FromUptimeMillis(int64_t uptime_millis_value);
1221
1222 #endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH)
1223
1224 #if BUILDFLAG(IS_ANDROID)
1225 // Converts to TimeTicks the value obtained from System.nanoTime(). This
1226 // conversion will be monotonic in relation to previously obtained
1227 // TimeTicks::Now() values as the clocks are based on the same posix monotonic
1228 // clock, with nanoTime() potentially providing higher resolution.
1229 static TimeTicks FromJavaNanoTime(int64_t nano_time_value);
1230
1231 // Truncates the TimeTicks value to the precision of SystemClock#uptimeMillis.
1232 // Note that the clocks already share the same monotonic clock source.
1233 jlong ToUptimeMillis() const;
1234
1235 // Returns the TimeTicks value as microseconds in the timebase of
1236 // SystemClock#uptimeMillis.
1237 // Note that the clocks already share the same monotonic clock source.
1238 //
1239 // System.nanoTime() may be used to get sub-millisecond precision in Java code
1240 // and may be compared against this value as the two share the same clock
1241 // source (though be sure to convert nanos to micros).
1242 jlong ToUptimeMicros() const;
1243
1244 #endif // BUILDFLAG(IS_ANDROID)
1245
1246 // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because
1247 // Time and TimeTicks respond differently to user-set time and NTP
1248 // adjustments, this number is only an estimate. Nevertheless, this can be
1249 // useful when you need to relate the value of TimeTicks to a real time and
1250 // date. Note: Upon first invocation, this function takes a snapshot of the
1251 // realtime clock to establish a reference point. This function will return
1252 // the same value for the duration of the application, but will be different
1253 // in future application runs.
1254 static TimeTicks UnixEpoch();
1255
1256 static void SetSharedUnixEpoch(TimeTicks);
1257
1258 // Returns |this| snapped to the next tick, given a |tick_phase| and
1259 // repeating |tick_interval| in both directions. |this| may be before,
1260 // after, or equal to the |tick_phase|.
1261 TimeTicks SnappedToNextTick(TimeTicks tick_phase,
1262 TimeDelta tick_interval) const;
1263
1264 // Returns an enum indicating the underlying clock being used to generate
1265 // TimeTicks timestamps. This function should only be used for debugging and
1266 // logging purposes.
1267 static Clock GetClock();
1268
1269 // Converts an integer value representing TimeTicks to a class. This may be
1270 // used when deserializing a |TimeTicks| structure, using a value known to be
1271 // compatible. It is not provided as a constructor because the integer type
1272 // may be unclear from the perspective of a caller.
1273 //
1274 // DEPRECATED - Do not use in new code. For deserializing TimeTicks values,
1275 // prefer TimeTicks + TimeDelta(); however, be aware that the origin is not
1276 // fixed and may vary. Serializing for persistence is strongly discouraged.
1277 // http://crbug.com/634507
FromInternalValue(int64_t us)1278 static constexpr TimeTicks FromInternalValue(int64_t us) {
1279 return TimeTicks(us);
1280 }
1281
1282 protected:
1283 #if BUILDFLAG(IS_WIN)
1284 typedef DWORD (*TickFunctionType)(void);
1285 static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
1286 #endif
1287
1288 private:
1289 friend class time_internal::TimeBase<TimeTicks>;
1290
1291 // Please use Now() to create a new object. This is for internal use
1292 // and testing.
TimeTicks(int64_t us)1293 constexpr explicit TimeTicks(int64_t us) : TimeBase(us) {}
1294 };
1295
1296 // For logging use only.
1297 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
1298
1299 // LiveTicks ------------------------------------------------------------------
1300
1301 // Behaves similarly to `TimeTicks` (a monotonically non-decreasing clock time)
1302 // with the main difference being that `LiveTicks` is guaranteed not to advance
1303 // while the system is suspended.
1304 class BASE_EXPORT LiveTicks : public time_internal::TimeBase<LiveTicks> {
1305 public:
LiveTicks()1306 constexpr LiveTicks() : TimeBase(0) {}
1307 static LiveTicks Now();
1308
1309 private:
1310 friend class time_internal::TimeBase<LiveTicks>;
1311
1312 // Please use Now() to create a new object. This is for internal use
1313 // and testing.
LiveTicks(int64_t us)1314 constexpr explicit LiveTicks(int64_t us) : TimeBase(us) {}
1315 };
1316
1317 // ThreadTicks ----------------------------------------------------------------
1318
1319 // Represents a clock, specific to a particular thread, than runs only while the
1320 // thread is running.
1321 class BASE_EXPORT ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
1322 public:
ThreadTicks()1323 constexpr ThreadTicks() : TimeBase(0) {}
1324
1325 // Returns true if ThreadTicks::Now() is supported on this system.
IsSupported()1326 [[nodiscard]] static bool IsSupported() {
1327 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
1328 BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA)
1329 return true;
1330 #elif BUILDFLAG(IS_WIN)
1331 return IsSupportedWin();
1332 #else
1333 return false;
1334 #endif
1335 }
1336
1337 // Waits until the initialization is completed. Needs to be guarded with a
1338 // call to IsSupported().
WaitUntilInitialized()1339 static void WaitUntilInitialized() {
1340 #if BUILDFLAG(IS_WIN)
1341 WaitUntilInitializedWin();
1342 #endif
1343 }
1344
1345 // Returns thread-specific CPU-time on systems that support this feature.
1346 // Needs to be guarded with a call to IsSupported(). Use this timer
1347 // to (approximately) measure how much time the calling thread spent doing
1348 // actual work vs. being de-scheduled. May return bogus results if the thread
1349 // migrates to another CPU between two calls. Returns an empty ThreadTicks
1350 // object until the initialization is completed. If a clock reading is
1351 // absolutely needed, call WaitUntilInitialized() before this method.
1352 static ThreadTicks Now();
1353
1354 #if BUILDFLAG(IS_WIN)
1355 // Similar to Now() above except this returns thread-specific CPU time for an
1356 // arbitrary thread. All comments for Now() method above apply apply to this
1357 // method as well.
1358 static ThreadTicks GetForThread(const PlatformThreadHandle& thread_handle);
1359 #endif
1360
1361 // Converts an integer value representing ThreadTicks to a class. This may be
1362 // used when deserializing a |ThreadTicks| structure, using a value known to
1363 // be compatible. It is not provided as a constructor because the integer type
1364 // may be unclear from the perspective of a caller.
1365 //
1366 // DEPRECATED - Do not use in new code. For deserializing ThreadTicks values,
1367 // prefer ThreadTicks + TimeDelta(); however, be aware that the origin is not
1368 // fixed and may vary. Serializing for persistence is strongly
1369 // discouraged. http://crbug.com/634507
FromInternalValue(int64_t us)1370 static constexpr ThreadTicks FromInternalValue(int64_t us) {
1371 return ThreadTicks(us);
1372 }
1373
1374 private:
1375 friend class time_internal::TimeBase<ThreadTicks>;
1376
1377 // Please use Now() or GetForThread() to create a new object. This is for
1378 // internal use and testing.
ThreadTicks(int64_t us)1379 constexpr explicit ThreadTicks(int64_t us) : TimeBase(us) {}
1380
1381 #if BUILDFLAG(IS_WIN)
1382 [[nodiscard]] static bool IsSupportedWin();
1383 static void WaitUntilInitializedWin();
1384 #endif
1385 };
1386
1387 // For logging use only.
1388 BASE_EXPORT std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
1389
1390 } // namespace base
1391
1392 #endif // BASE_TIME_TIME_H_
1393