time.h revision a36e5920737c6adbddd3e43b760e5de8431db6e0
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 time, internally represented as
6// microseconds (s/1,000,000) since the Windows epoch (1601-01-01 00:00:00 UTC)
7// (See http://crbug.com/14734).  System-dependent clock interface routines are
8// defined in time_PLATFORM.cc.
9//
10// TimeDelta represents a duration of time, internally represented in
11// microseconds.
12//
13// TimeTicks represents an abstract time that is most of the time incrementing
14// for use in measuring time durations. It is internally represented in
15// microseconds.  It can not be converted to a human-readable time, but is
16// guaranteed not to decrease (if the user changes the computer clock,
17// Time::Now() may actually decrease or jump).  But note that TimeTicks may
18// "stand still", for example if the computer suspended.
19//
20// These classes are represented as only a 64-bit value, so they can be
21// efficiently passed by value.
22
23#ifndef BASE_TIME_TIME_H_
24#define BASE_TIME_TIME_H_
25
26#include <time.h>
27
28#include "base/atomicops.h"
29#include "base/base_export.h"
30#include "base/basictypes.h"
31
32#if defined(OS_MACOSX)
33#include <CoreFoundation/CoreFoundation.h>
34// Avoid Mac system header macro leak.
35#undef TYPE_BOOL
36#endif
37
38#if defined(OS_POSIX)
39#include <unistd.h>
40#include <sys/time.h>
41#endif
42
43#if defined(OS_WIN)
44// For FILETIME in FromFileTime, until it moves to a new converter class.
45// See TODO(iyengar) below.
46#include <windows.h>
47#endif
48
49#include <limits>
50
51namespace base {
52
53class Time;
54class TimeTicks;
55
56// TimeDelta ------------------------------------------------------------------
57
58class BASE_EXPORT TimeDelta {
59 public:
60  TimeDelta() : delta_(0) {
61  }
62
63  // Converts units of time to TimeDeltas.
64  static TimeDelta FromDays(int64 days);
65  static TimeDelta FromHours(int64 hours);
66  static TimeDelta FromMinutes(int64 minutes);
67  static TimeDelta FromSeconds(int64 secs);
68  static TimeDelta FromMilliseconds(int64 ms);
69  static TimeDelta FromMicroseconds(int64 us);
70#if defined(OS_WIN)
71  static TimeDelta FromQPCValue(LONGLONG qpc_value);
72#endif
73
74  // Converts an integer value representing TimeDelta to a class. This is used
75  // when deserializing a |TimeDelta| structure, using a value known to be
76  // compatible. It is not provided as a constructor because the integer type
77  // may be unclear from the perspective of a caller.
78  static TimeDelta FromInternalValue(int64 delta) {
79    return TimeDelta(delta);
80  }
81
82  // Returns the internal numeric value of the TimeDelta object. Please don't
83  // use this and do arithmetic on it, as it is more error prone than using the
84  // provided operators.
85  // For serializing, use FromInternalValue to reconstitute.
86  int64 ToInternalValue() const {
87    return delta_;
88  }
89
90#if defined(OS_POSIX)
91  struct timespec ToTimeSpec() const;
92#endif
93
94  // Returns the time delta in some unit. The F versions return a floating
95  // point value, the "regular" versions return a rounded-down value.
96  //
97  // InMillisecondsRoundedUp() instead returns an integer that is rounded up
98  // to the next full millisecond.
99  int InDays() const;
100  int InHours() const;
101  int InMinutes() const;
102  double InSecondsF() const;
103  int64 InSeconds() const;
104  double InMillisecondsF() const;
105  int64 InMilliseconds() const;
106  int64 InMillisecondsRoundedUp() const;
107  int64 InMicroseconds() const;
108
109  TimeDelta& operator=(TimeDelta other) {
110    delta_ = other.delta_;
111    return *this;
112  }
113
114  // Computations with other deltas.
115  TimeDelta operator+(TimeDelta other) const {
116    return TimeDelta(delta_ + other.delta_);
117  }
118  TimeDelta operator-(TimeDelta other) const {
119    return TimeDelta(delta_ - other.delta_);
120  }
121
122  TimeDelta& operator+=(TimeDelta other) {
123    delta_ += other.delta_;
124    return *this;
125  }
126  TimeDelta& operator-=(TimeDelta other) {
127    delta_ -= other.delta_;
128    return *this;
129  }
130  TimeDelta operator-() const {
131    return TimeDelta(-delta_);
132  }
133
134  // Computations with ints, note that we only allow multiplicative operations
135  // with ints, and additive operations with other deltas.
136  TimeDelta operator*(int64 a) const {
137    return TimeDelta(delta_ * a);
138  }
139  TimeDelta operator/(int64 a) const {
140    return TimeDelta(delta_ / a);
141  }
142  TimeDelta& operator*=(int64 a) {
143    delta_ *= a;
144    return *this;
145  }
146  TimeDelta& operator/=(int64 a) {
147    delta_ /= a;
148    return *this;
149  }
150  int64 operator/(TimeDelta a) const {
151    return delta_ / a.delta_;
152  }
153
154  // Defined below because it depends on the definition of the other classes.
155  Time operator+(Time t) const;
156  TimeTicks operator+(TimeTicks t) const;
157
158  // Comparison operators.
159  bool operator==(TimeDelta other) const {
160    return delta_ == other.delta_;
161  }
162  bool operator!=(TimeDelta other) const {
163    return delta_ != other.delta_;
164  }
165  bool operator<(TimeDelta other) const {
166    return delta_ < other.delta_;
167  }
168  bool operator<=(TimeDelta other) const {
169    return delta_ <= other.delta_;
170  }
171  bool operator>(TimeDelta other) const {
172    return delta_ > other.delta_;
173  }
174  bool operator>=(TimeDelta other) const {
175    return delta_ >= other.delta_;
176  }
177
178 private:
179  friend class Time;
180  friend class TimeTicks;
181  friend TimeDelta operator*(int64 a, TimeDelta td);
182
183  // Constructs a delta given the duration in microseconds. This is private
184  // to avoid confusion by callers with an integer constructor. Use
185  // FromSeconds, FromMilliseconds, etc. instead.
186  explicit TimeDelta(int64 delta_us) : delta_(delta_us) {
187  }
188
189  // Delta in microseconds.
190  int64 delta_;
191};
192
193inline TimeDelta operator*(int64 a, TimeDelta td) {
194  return TimeDelta(a * td.delta_);
195}
196
197// Time -----------------------------------------------------------------------
198
199// Represents a wall clock time.
200class BASE_EXPORT Time {
201 public:
202  static const int64 kMillisecondsPerSecond = 1000;
203  static const int64 kMicrosecondsPerMillisecond = 1000;
204  static const int64 kMicrosecondsPerSecond = kMicrosecondsPerMillisecond *
205                                              kMillisecondsPerSecond;
206  static const int64 kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
207  static const int64 kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
208  static const int64 kMicrosecondsPerDay = kMicrosecondsPerHour * 24;
209  static const int64 kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
210  static const int64 kNanosecondsPerMicrosecond = 1000;
211  static const int64 kNanosecondsPerSecond = kNanosecondsPerMicrosecond *
212                                             kMicrosecondsPerSecond;
213
214#if !defined(OS_WIN)
215  // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
216  // the Posix delta of 1970. This is used for migrating between the old
217  // 1970-based epochs to the new 1601-based ones. It should be removed from
218  // this global header and put in the platform-specific ones when we remove the
219  // migration code.
220  static const int64 kWindowsEpochDeltaMicroseconds;
221#endif
222
223  // Represents an exploded time that can be formatted nicely. This is kind of
224  // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
225  // additions and changes to prevent errors.
226  struct BASE_EXPORT Exploded {
227    int year;          // Four digit year "2007"
228    int month;         // 1-based month (values 1 = January, etc.)
229    int day_of_week;   // 0-based day of week (0 = Sunday, etc.)
230    int day_of_month;  // 1-based day of month (1-31)
231    int hour;          // Hour within the current day (0-23)
232    int minute;        // Minute within the current hour (0-59)
233    int second;        // Second within the current minute (0-59 plus leap
234                       //   seconds which may take it up to 60).
235    int millisecond;   // Milliseconds within the current second (0-999)
236
237    // A cursory test for whether the data members are within their
238    // respective ranges. A 'true' return value does not guarantee the
239    // Exploded value can be successfully converted to a Time value.
240    bool HasValidValues() const;
241  };
242
243  // Contains the NULL time. Use Time::Now() to get the current time.
244  Time() : us_(0) {
245  }
246
247  // Returns true if the time object has not been initialized.
248  bool is_null() const {
249    return us_ == 0;
250  }
251
252  // Returns true if the time object is the maximum time.
253  bool is_max() const {
254    return us_ == std::numeric_limits<int64>::max();
255  }
256
257  // Returns the time for epoch in Unix-like system (Jan 1, 1970).
258  static Time UnixEpoch();
259
260  // Returns the current time. Watch out, the system might adjust its clock
261  // in which case time will actually go backwards. We don't guarantee that
262  // times are increasing, or that two calls to Now() won't be the same.
263  static Time Now();
264
265  // Returns the maximum time, which should be greater than any reasonable time
266  // with which we might compare it.
267  static Time Max();
268
269  // Returns the current time. Same as Now() except that this function always
270  // uses system time so that there are no discrepancies between the returned
271  // time and system time even on virtual environments including our test bot.
272  // For timing sensitive unittests, this function should be used.
273  static Time NowFromSystemTime();
274
275  // Converts to/from time_t in UTC and a Time class.
276  // TODO(brettw) this should be removed once everybody starts using the |Time|
277  // class.
278  static Time FromTimeT(time_t tt);
279  time_t ToTimeT() const;
280
281  // Converts time to/from a double which is the number of seconds since epoch
282  // (Jan 1, 1970).  Webkit uses this format to represent time.
283  // Because WebKit initializes double time value to 0 to indicate "not
284  // initialized", we map it to empty Time object that also means "not
285  // initialized".
286  static Time FromDoubleT(double dt);
287  double ToDoubleT() const;
288
289#if defined(OS_POSIX)
290  // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
291  // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
292  // having a 1 second resolution, which agrees with
293  // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
294  static Time FromTimeSpec(const timespec& ts);
295#endif
296
297  // Converts to/from the Javascript convention for times, a number of
298  // milliseconds since the epoch:
299  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
300  static Time FromJsTime(double ms_since_epoch);
301  double ToJsTime() const;
302
303#if defined(OS_POSIX)
304  static Time FromTimeVal(struct timeval t);
305  struct timeval ToTimeVal() const;
306#endif
307
308#if defined(OS_MACOSX)
309  static Time FromCFAbsoluteTime(CFAbsoluteTime t);
310  CFAbsoluteTime ToCFAbsoluteTime() const;
311#endif
312
313#if defined(OS_WIN)
314  static Time FromFileTime(FILETIME ft);
315  FILETIME ToFileTime() const;
316
317  // The minimum time of a low resolution timer.  This is basically a windows
318  // constant of ~15.6ms.  While it does vary on some older OS versions, we'll
319  // treat it as static across all windows versions.
320  static const int kMinLowResolutionThresholdMs = 16;
321
322  // Enable or disable Windows high resolution timer. If the high resolution
323  // timer is not enabled, calls to ActivateHighResolutionTimer will fail.
324  // When disabling the high resolution timer, this function will not cause
325  // the high resolution timer to be deactivated, but will prevent future
326  // activations.
327  // Must be called from the main thread.
328  // For more details see comments in time_win.cc.
329  static void EnableHighResolutionTimer(bool enable);
330
331  // Activates or deactivates the high resolution timer based on the |activate|
332  // flag.  If the HighResolutionTimer is not Enabled (see
333  // EnableHighResolutionTimer), this function will return false.  Otherwise
334  // returns true.  Each successful activate call must be paired with a
335  // subsequent deactivate call.
336  // All callers to activate the high resolution timer must eventually call
337  // this function to deactivate the high resolution timer.
338  static bool ActivateHighResolutionTimer(bool activate);
339
340  // Returns true if the high resolution timer is both enabled and activated.
341  // This is provided for testing only, and is not tracked in a thread-safe
342  // way.
343  static bool IsHighResolutionTimerInUse();
344#endif
345
346  // Converts an exploded structure representing either the local time or UTC
347  // into a Time class.
348  static Time FromUTCExploded(const Exploded& exploded) {
349    return FromExploded(false, exploded);
350  }
351  static Time FromLocalExploded(const Exploded& exploded) {
352    return FromExploded(true, exploded);
353  }
354
355  // Converts an integer value representing Time to a class. This is used
356  // when deserializing a |Time| structure, using a value known to be
357  // compatible. It is not provided as a constructor because the integer type
358  // may be unclear from the perspective of a caller.
359  static Time FromInternalValue(int64 us) {
360    return Time(us);
361  }
362
363  // Converts a string representation of time to a Time object.
364  // An example of a time string which is converted is as below:-
365  // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
366  // in the input string, FromString assumes local time and FromUTCString
367  // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
368  // specified in RFC822) is treated as if the timezone is not specified.
369  // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
370  // a new time converter class.
371  static bool FromString(const char* time_string, Time* parsed_time) {
372    return FromStringInternal(time_string, true, parsed_time);
373  }
374  static bool FromUTCString(const char* time_string, Time* parsed_time) {
375    return FromStringInternal(time_string, false, parsed_time);
376  }
377
378  // For serializing, use FromInternalValue to reconstitute. Please don't use
379  // this and do arithmetic on it, as it is more error prone than using the
380  // provided operators.
381  int64 ToInternalValue() const {
382    return us_;
383  }
384
385  // Fills the given exploded structure with either the local time or UTC from
386  // this time structure (containing UTC).
387  void UTCExplode(Exploded* exploded) const {
388    return Explode(false, exploded);
389  }
390  void LocalExplode(Exploded* exploded) const {
391    return Explode(true, exploded);
392  }
393
394  // Rounds this time down to the nearest day in local time. It will represent
395  // midnight on that day.
396  Time LocalMidnight() const;
397
398  Time& operator=(Time other) {
399    us_ = other.us_;
400    return *this;
401  }
402
403  // Compute the difference between two times.
404  TimeDelta operator-(Time other) const {
405    return TimeDelta(us_ - other.us_);
406  }
407
408  // Modify by some time delta.
409  Time& operator+=(TimeDelta delta) {
410    us_ += delta.delta_;
411    return *this;
412  }
413  Time& operator-=(TimeDelta delta) {
414    us_ -= delta.delta_;
415    return *this;
416  }
417
418  // Return a new time modified by some delta.
419  Time operator+(TimeDelta delta) const {
420    return Time(us_ + delta.delta_);
421  }
422  Time operator-(TimeDelta delta) const {
423    return Time(us_ - delta.delta_);
424  }
425
426  // Comparison operators
427  bool operator==(Time other) const {
428    return us_ == other.us_;
429  }
430  bool operator!=(Time other) const {
431    return us_ != other.us_;
432  }
433  bool operator<(Time other) const {
434    return us_ < other.us_;
435  }
436  bool operator<=(Time other) const {
437    return us_ <= other.us_;
438  }
439  bool operator>(Time other) const {
440    return us_ > other.us_;
441  }
442  bool operator>=(Time other) const {
443    return us_ >= other.us_;
444  }
445
446 private:
447  friend class TimeDelta;
448
449  explicit Time(int64 us) : us_(us) {
450  }
451
452  // Explodes the given time to either local time |is_local = true| or UTC
453  // |is_local = false|.
454  void Explode(bool is_local, Exploded* exploded) const;
455
456  // Unexplodes a given time assuming the source is either local time
457  // |is_local = true| or UTC |is_local = false|.
458  static Time FromExploded(bool is_local, const Exploded& exploded);
459
460  // Converts a string representation of time to a Time object.
461  // An example of a time string which is converted is as below:-
462  // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
463  // in the input string, local time |is_local = true| or
464  // UTC |is_local = false| is assumed. A timezone that cannot be parsed
465  // (e.g. "UTC" which is not specified in RFC822) is treated as if the
466  // timezone is not specified.
467  static bool FromStringInternal(const char* time_string,
468                                 bool is_local,
469                                 Time* parsed_time);
470
471  // The representation of Jan 1, 1970 UTC in microseconds since the
472  // platform-dependent epoch.
473  static const int64 kTimeTToMicrosecondsOffset;
474
475#if defined(OS_WIN)
476  // Indicates whether fast timers are usable right now.  For instance,
477  // when using battery power, we might elect to prevent high speed timers
478  // which would draw more power.
479  static bool high_resolution_timer_enabled_;
480  // Count of activations on the high resolution timer.  Only use in tests
481  // which are single threaded.
482  static int high_resolution_timer_activated_;
483#endif
484
485  // Time in microseconds in UTC.
486  int64 us_;
487};
488
489// Inline the TimeDelta factory methods, for fast TimeDelta construction.
490
491// static
492inline TimeDelta TimeDelta::FromDays(int64 days) {
493  return TimeDelta(days * Time::kMicrosecondsPerDay);
494}
495
496// static
497inline TimeDelta TimeDelta::FromHours(int64 hours) {
498  return TimeDelta(hours * Time::kMicrosecondsPerHour);
499}
500
501// static
502inline TimeDelta TimeDelta::FromMinutes(int64 minutes) {
503  return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
504}
505
506// static
507inline TimeDelta TimeDelta::FromSeconds(int64 secs) {
508  return TimeDelta(secs * Time::kMicrosecondsPerSecond);
509}
510
511// static
512inline TimeDelta TimeDelta::FromMilliseconds(int64 ms) {
513  return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
514}
515
516// static
517inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
518  return TimeDelta(us);
519}
520
521inline Time TimeDelta::operator+(Time t) const {
522  return Time(t.us_ + delta_);
523}
524
525// TimeTicks ------------------------------------------------------------------
526
527class BASE_EXPORT TimeTicks {
528 public:
529  TimeTicks() : ticks_(0) {
530  }
531
532  // Platform-dependent tick count representing "right now."
533  // The resolution of this clock is ~1-15ms.  Resolution varies depending
534  // on hardware/operating system configuration.
535  static TimeTicks Now();
536
537  // Returns a platform-dependent high-resolution tick count. Implementation
538  // is hardware dependent and may or may not return sub-millisecond
539  // resolution.  THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND
540  // SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED.
541  static TimeTicks HighResNow();
542
543  // Returns true if ThreadNow() is supported on this system.
544  static bool IsThreadNowSupported() {
545#if defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)
546    return true;
547#else
548    return false;
549#endif
550  }
551
552  // Returns thread-specific CPU-time on systems that support this feature.
553  // Needs to be guarded with a call to IsThreadNowSupported(). Use this timer
554  // to (approximately) measure how much time the calling thread spent doing
555  // actual work vs. being de-scheduled. May return bogus results if the thread
556  // migrates to another CPU between two calls.
557  static TimeTicks ThreadNow();
558
559  // Returns the current system trace time or, if none is defined, the current
560  // high-res time (i.e. HighResNow()). On systems where a global trace clock
561  // is defined, timestamping TraceEvents's with this value guarantees
562  // synchronization between events collected inside chrome and events
563  // collected outside (e.g. kernel, X server).
564  static TimeTicks NowFromSystemTraceTime();
565
566#if defined(OS_WIN)
567  // Get the absolute value of QPC time drift. For testing.
568  static int64 GetQPCDriftMicroseconds();
569
570  static TimeTicks FromQPCValue(LONGLONG qpc_value);
571
572  // Returns true if the high resolution clock is working on this system.
573  // This is only for testing.
574  static bool IsHighResClockWorking();
575#endif
576
577  // Returns true if this object has not been initialized.
578  bool is_null() const {
579    return ticks_ == 0;
580  }
581
582  // Converts an integer value representing TimeTicks to a class. This is used
583  // when deserializing a |TimeTicks| structure, using a value known to be
584  // compatible. It is not provided as a constructor because the integer type
585  // may be unclear from the perspective of a caller.
586  static TimeTicks FromInternalValue(int64 ticks) {
587    return TimeTicks(ticks);
588  }
589
590  // Returns the internal numeric value of the TimeTicks object.
591  // For serializing, use FromInternalValue to reconstitute.
592  int64 ToInternalValue() const {
593    return ticks_;
594  }
595
596  TimeTicks& operator=(TimeTicks other) {
597    ticks_ = other.ticks_;
598    return *this;
599  }
600
601  // Compute the difference between two times.
602  TimeDelta operator-(TimeTicks other) const {
603    return TimeDelta(ticks_ - other.ticks_);
604  }
605
606  // Modify by some time delta.
607  TimeTicks& operator+=(TimeDelta delta) {
608    ticks_ += delta.delta_;
609    return *this;
610  }
611  TimeTicks& operator-=(TimeDelta delta) {
612    ticks_ -= delta.delta_;
613    return *this;
614  }
615
616  // Return a new TimeTicks modified by some delta.
617  TimeTicks operator+(TimeDelta delta) const {
618    return TimeTicks(ticks_ + delta.delta_);
619  }
620  TimeTicks operator-(TimeDelta delta) const {
621    return TimeTicks(ticks_ - delta.delta_);
622  }
623
624  // Comparison operators
625  bool operator==(TimeTicks other) const {
626    return ticks_ == other.ticks_;
627  }
628  bool operator!=(TimeTicks other) const {
629    return ticks_ != other.ticks_;
630  }
631  bool operator<(TimeTicks other) const {
632    return ticks_ < other.ticks_;
633  }
634  bool operator<=(TimeTicks other) const {
635    return ticks_ <= other.ticks_;
636  }
637  bool operator>(TimeTicks other) const {
638    return ticks_ > other.ticks_;
639  }
640  bool operator>=(TimeTicks other) const {
641    return ticks_ >= other.ticks_;
642  }
643
644 protected:
645  friend class TimeDelta;
646
647  // Please use Now() to create a new object. This is for internal use
648  // and testing. Ticks is in microseconds.
649  explicit TimeTicks(int64 ticks) : ticks_(ticks) {
650  }
651
652  // Tick count in microseconds.
653  int64 ticks_;
654
655#if defined(OS_WIN)
656  typedef DWORD (*TickFunctionType)(void);
657  static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
658#endif
659};
660
661inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
662  return TimeTicks(t.ticks_ + delta_);
663}
664
665}  // namespace base
666
667#endif  // BASE_TIME_TIME_H_
668