time.h 43 KB

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