time.h 46 KB

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