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