Coverage Report

Created: 2018-09-25 14:53

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