blob: 6d5e538970cfd8e8b3608c196b79c361a44c4107 [file] [log] [blame]
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001// Copyright 2013 the V8 project 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#include "src/base/platform/time.h"
6
7#if V8_OS_POSIX
8#include <fcntl.h> // for O_RDONLY
9#include <sys/time.h>
10#include <unistd.h>
11#endif
12#if V8_OS_MACOSX
13#include <mach/mach_time.h>
14#endif
15
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000016#include <cstring>
17#include <ostream>
Ben Murdochb8a8cc12014-11-26 15:28:44 +000018
19#if V8_OS_WIN
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000020#include "src/base/atomicops.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000021#include "src/base/lazy-instance.h"
22#include "src/base/win32-headers.h"
23#endif
24#include "src/base/cpu.h"
25#include "src/base/logging.h"
26#include "src/base/platform/platform.h"
27
28namespace v8 {
29namespace base {
30
31TimeDelta TimeDelta::FromDays(int days) {
32 return TimeDelta(days * Time::kMicrosecondsPerDay);
33}
34
35
36TimeDelta TimeDelta::FromHours(int hours) {
37 return TimeDelta(hours * Time::kMicrosecondsPerHour);
38}
39
40
41TimeDelta TimeDelta::FromMinutes(int minutes) {
42 return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
43}
44
45
46TimeDelta TimeDelta::FromSeconds(int64_t seconds) {
47 return TimeDelta(seconds * Time::kMicrosecondsPerSecond);
48}
49
50
51TimeDelta TimeDelta::FromMilliseconds(int64_t milliseconds) {
52 return TimeDelta(milliseconds * Time::kMicrosecondsPerMillisecond);
53}
54
55
56TimeDelta TimeDelta::FromNanoseconds(int64_t nanoseconds) {
57 return TimeDelta(nanoseconds / Time::kNanosecondsPerMicrosecond);
58}
59
60
61int TimeDelta::InDays() const {
62 return static_cast<int>(delta_ / Time::kMicrosecondsPerDay);
63}
64
65
66int TimeDelta::InHours() const {
67 return static_cast<int>(delta_ / Time::kMicrosecondsPerHour);
68}
69
70
71int TimeDelta::InMinutes() const {
72 return static_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
73}
74
75
76double TimeDelta::InSecondsF() const {
77 return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond;
78}
79
80
81int64_t TimeDelta::InSeconds() const {
82 return delta_ / Time::kMicrosecondsPerSecond;
83}
84
85
86double TimeDelta::InMillisecondsF() const {
87 return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond;
88}
89
90
91int64_t TimeDelta::InMilliseconds() const {
92 return delta_ / Time::kMicrosecondsPerMillisecond;
93}
94
95
96int64_t TimeDelta::InNanoseconds() const {
97 return delta_ * Time::kNanosecondsPerMicrosecond;
98}
99
100
101#if V8_OS_MACOSX
102
103TimeDelta TimeDelta::FromMachTimespec(struct mach_timespec ts) {
104 DCHECK_GE(ts.tv_nsec, 0);
105 DCHECK_LT(ts.tv_nsec,
106 static_cast<long>(Time::kNanosecondsPerSecond)); // NOLINT
107 return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond +
108 ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
109}
110
111
112struct mach_timespec TimeDelta::ToMachTimespec() const {
113 struct mach_timespec ts;
114 DCHECK(delta_ >= 0);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000115 ts.tv_sec = static_cast<unsigned>(delta_ / Time::kMicrosecondsPerSecond);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000116 ts.tv_nsec = (delta_ % Time::kMicrosecondsPerSecond) *
117 Time::kNanosecondsPerMicrosecond;
118 return ts;
119}
120
121#endif // V8_OS_MACOSX
122
123
124#if V8_OS_POSIX
125
126TimeDelta TimeDelta::FromTimespec(struct timespec ts) {
127 DCHECK_GE(ts.tv_nsec, 0);
128 DCHECK_LT(ts.tv_nsec,
129 static_cast<long>(Time::kNanosecondsPerSecond)); // NOLINT
130 return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond +
131 ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
132}
133
134
135struct timespec TimeDelta::ToTimespec() const {
136 struct timespec ts;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000137 ts.tv_sec = static_cast<time_t>(delta_ / Time::kMicrosecondsPerSecond);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000138 ts.tv_nsec = (delta_ % Time::kMicrosecondsPerSecond) *
139 Time::kNanosecondsPerMicrosecond;
140 return ts;
141}
142
143#endif // V8_OS_POSIX
144
145
146#if V8_OS_WIN
147
148// We implement time using the high-resolution timers so that we can get
149// timeouts which are smaller than 10-15ms. To avoid any drift, we
150// periodically resync the internal clock to the system clock.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000151class Clock final {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000152 public:
153 Clock() : initial_ticks_(GetSystemTicks()), initial_time_(GetSystemTime()) {}
154
155 Time Now() {
156 // Time between resampling the un-granular clock for this API (1 minute).
157 const TimeDelta kMaxElapsedTime = TimeDelta::FromMinutes(1);
158
159 LockGuard<Mutex> lock_guard(&mutex_);
160
161 // Determine current time and ticks.
162 TimeTicks ticks = GetSystemTicks();
163 Time time = GetSystemTime();
164
165 // Check if we need to synchronize with the system clock due to a backwards
166 // time change or the amount of time elapsed.
167 TimeDelta elapsed = ticks - initial_ticks_;
168 if (time < initial_time_ || elapsed > kMaxElapsedTime) {
169 initial_ticks_ = ticks;
170 initial_time_ = time;
171 return time;
172 }
173
174 return initial_time_ + elapsed;
175 }
176
177 Time NowFromSystemTime() {
178 LockGuard<Mutex> lock_guard(&mutex_);
179 initial_ticks_ = GetSystemTicks();
180 initial_time_ = GetSystemTime();
181 return initial_time_;
182 }
183
184 private:
185 static TimeTicks GetSystemTicks() {
186 return TimeTicks::Now();
187 }
188
189 static Time GetSystemTime() {
190 FILETIME ft;
191 ::GetSystemTimeAsFileTime(&ft);
192 return Time::FromFiletime(ft);
193 }
194
195 TimeTicks initial_ticks_;
196 Time initial_time_;
197 Mutex mutex_;
198};
199
200
201static LazyStaticInstance<Clock, DefaultConstructTrait<Clock>,
202 ThreadSafeInitOnceTrait>::type clock =
203 LAZY_STATIC_INSTANCE_INITIALIZER;
204
205
206Time Time::Now() {
207 return clock.Pointer()->Now();
208}
209
210
211Time Time::NowFromSystemTime() {
212 return clock.Pointer()->NowFromSystemTime();
213}
214
215
216// Time between windows epoch and standard epoch.
217static const int64_t kTimeToEpochInMicroseconds = V8_INT64_C(11644473600000000);
218
219
220Time Time::FromFiletime(FILETIME ft) {
221 if (ft.dwLowDateTime == 0 && ft.dwHighDateTime == 0) {
222 return Time();
223 }
224 if (ft.dwLowDateTime == std::numeric_limits<DWORD>::max() &&
225 ft.dwHighDateTime == std::numeric_limits<DWORD>::max()) {
226 return Max();
227 }
228 int64_t us = (static_cast<uint64_t>(ft.dwLowDateTime) +
229 (static_cast<uint64_t>(ft.dwHighDateTime) << 32)) / 10;
230 return Time(us - kTimeToEpochInMicroseconds);
231}
232
233
234FILETIME Time::ToFiletime() const {
235 DCHECK(us_ >= 0);
236 FILETIME ft;
237 if (IsNull()) {
238 ft.dwLowDateTime = 0;
239 ft.dwHighDateTime = 0;
240 return ft;
241 }
242 if (IsMax()) {
243 ft.dwLowDateTime = std::numeric_limits<DWORD>::max();
244 ft.dwHighDateTime = std::numeric_limits<DWORD>::max();
245 return ft;
246 }
247 uint64_t us = static_cast<uint64_t>(us_ + kTimeToEpochInMicroseconds) * 10;
248 ft.dwLowDateTime = static_cast<DWORD>(us);
249 ft.dwHighDateTime = static_cast<DWORD>(us >> 32);
250 return ft;
251}
252
253#elif V8_OS_POSIX
254
255Time Time::Now() {
256 struct timeval tv;
257 int result = gettimeofday(&tv, NULL);
258 DCHECK_EQ(0, result);
259 USE(result);
260 return FromTimeval(tv);
261}
262
263
264Time Time::NowFromSystemTime() {
265 return Now();
266}
267
268
269Time Time::FromTimespec(struct timespec ts) {
270 DCHECK(ts.tv_nsec >= 0);
271 DCHECK(ts.tv_nsec < static_cast<long>(kNanosecondsPerSecond)); // NOLINT
272 if (ts.tv_nsec == 0 && ts.tv_sec == 0) {
273 return Time();
274 }
275 if (ts.tv_nsec == static_cast<long>(kNanosecondsPerSecond - 1) && // NOLINT
276 ts.tv_sec == std::numeric_limits<time_t>::max()) {
277 return Max();
278 }
279 return Time(ts.tv_sec * kMicrosecondsPerSecond +
280 ts.tv_nsec / kNanosecondsPerMicrosecond);
281}
282
283
284struct timespec Time::ToTimespec() const {
285 struct timespec ts;
286 if (IsNull()) {
287 ts.tv_sec = 0;
288 ts.tv_nsec = 0;
289 return ts;
290 }
291 if (IsMax()) {
292 ts.tv_sec = std::numeric_limits<time_t>::max();
293 ts.tv_nsec = static_cast<long>(kNanosecondsPerSecond - 1); // NOLINT
294 return ts;
295 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000296 ts.tv_sec = static_cast<time_t>(us_ / kMicrosecondsPerSecond);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000297 ts.tv_nsec = (us_ % kMicrosecondsPerSecond) * kNanosecondsPerMicrosecond;
298 return ts;
299}
300
301
302Time Time::FromTimeval(struct timeval tv) {
303 DCHECK(tv.tv_usec >= 0);
304 DCHECK(tv.tv_usec < static_cast<suseconds_t>(kMicrosecondsPerSecond));
305 if (tv.tv_usec == 0 && tv.tv_sec == 0) {
306 return Time();
307 }
308 if (tv.tv_usec == static_cast<suseconds_t>(kMicrosecondsPerSecond - 1) &&
309 tv.tv_sec == std::numeric_limits<time_t>::max()) {
310 return Max();
311 }
312 return Time(tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec);
313}
314
315
316struct timeval Time::ToTimeval() const {
317 struct timeval tv;
318 if (IsNull()) {
319 tv.tv_sec = 0;
320 tv.tv_usec = 0;
321 return tv;
322 }
323 if (IsMax()) {
324 tv.tv_sec = std::numeric_limits<time_t>::max();
325 tv.tv_usec = static_cast<suseconds_t>(kMicrosecondsPerSecond - 1);
326 return tv;
327 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000328 tv.tv_sec = static_cast<time_t>(us_ / kMicrosecondsPerSecond);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000329 tv.tv_usec = us_ % kMicrosecondsPerSecond;
330 return tv;
331}
332
333#endif // V8_OS_WIN
334
335
336Time Time::FromJsTime(double ms_since_epoch) {
337 // The epoch is a valid time, so this constructor doesn't interpret
338 // 0 as the null time.
339 if (ms_since_epoch == std::numeric_limits<double>::max()) {
340 return Max();
341 }
342 return Time(
343 static_cast<int64_t>(ms_since_epoch * kMicrosecondsPerMillisecond));
344}
345
346
347double Time::ToJsTime() const {
348 if (IsNull()) {
349 // Preserve 0 so the invalid result doesn't depend on the platform.
350 return 0;
351 }
352 if (IsMax()) {
353 // Preserve max without offset to prevent overflow.
354 return std::numeric_limits<double>::max();
355 }
356 return static_cast<double>(us_) / kMicrosecondsPerMillisecond;
357}
358
359
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000360std::ostream& operator<<(std::ostream& os, const Time& time) {
361 return os << time.ToJsTime();
362}
363
364
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000365#if V8_OS_WIN
366
367class TickClock {
368 public:
369 virtual ~TickClock() {}
370 virtual int64_t Now() = 0;
371 virtual bool IsHighResolution() = 0;
372};
373
374
375// Overview of time counters:
376// (1) CPU cycle counter. (Retrieved via RDTSC)
377// The CPU counter provides the highest resolution time stamp and is the least
378// expensive to retrieve. However, the CPU counter is unreliable and should not
379// be used in production. Its biggest issue is that it is per processor and it
380// is not synchronized between processors. Also, on some computers, the counters
381// will change frequency due to thermal and power changes, and stop in some
382// states.
383//
384// (2) QueryPerformanceCounter (QPC). The QPC counter provides a high-
385// resolution (100 nanoseconds) time stamp but is comparatively more expensive
386// to retrieve. What QueryPerformanceCounter actually does is up to the HAL.
387// (with some help from ACPI).
388// According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx
389// in the worst case, it gets the counter from the rollover interrupt on the
390// programmable interrupt timer. In best cases, the HAL may conclude that the
391// RDTSC counter runs at a constant frequency, then it uses that instead. On
392// multiprocessor machines, it will try to verify the values returned from
393// RDTSC on each processor are consistent with each other, and apply a handful
394// of workarounds for known buggy hardware. In other words, QPC is supposed to
395// give consistent result on a multiprocessor computer, but it is unreliable in
396// reality due to bugs in BIOS or HAL on some, especially old computers.
397// With recent updates on HAL and newer BIOS, QPC is getting more reliable but
398// it should be used with caution.
399//
400// (3) System time. The system time provides a low-resolution (typically 10ms
401// to 55 milliseconds) time stamp but is comparatively less expensive to
402// retrieve and more reliable.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000403class HighResolutionTickClock final : public TickClock {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000404 public:
405 explicit HighResolutionTickClock(int64_t ticks_per_second)
406 : ticks_per_second_(ticks_per_second) {
407 DCHECK_LT(0, ticks_per_second);
408 }
409 virtual ~HighResolutionTickClock() {}
410
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000411 int64_t Now() override {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000412 LARGE_INTEGER now;
413 BOOL result = QueryPerformanceCounter(&now);
414 DCHECK(result);
415 USE(result);
416
417 // Intentionally calculate microseconds in a round about manner to avoid
418 // overflow and precision issues. Think twice before simplifying!
419 int64_t whole_seconds = now.QuadPart / ticks_per_second_;
420 int64_t leftover_ticks = now.QuadPart % ticks_per_second_;
421 int64_t ticks = (whole_seconds * Time::kMicrosecondsPerSecond) +
422 ((leftover_ticks * Time::kMicrosecondsPerSecond) / ticks_per_second_);
423
424 // Make sure we never return 0 here, so that TimeTicks::HighResolutionNow()
425 // will never return 0.
426 return ticks + 1;
427 }
428
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000429 bool IsHighResolution() override { return true; }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000430
431 private:
432 int64_t ticks_per_second_;
433};
434
435
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000436class RolloverProtectedTickClock final : public TickClock {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000437 public:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000438 RolloverProtectedTickClock() : rollover_(0) {}
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000439 virtual ~RolloverProtectedTickClock() {}
440
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000441 int64_t Now() override {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000442 // We use timeGetTime() to implement TimeTicks::Now(), which rolls over
443 // every ~49.7 days. We try to track rollover ourselves, which works if
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000444 // TimeTicks::Now() is called at least every 24 days.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000445 // Note that we do not use GetTickCount() here, since timeGetTime() gives
446 // more predictable delta values, as described here:
447 // http://blogs.msdn.com/b/larryosterman/archive/2009/09/02/what-s-the-difference-between-gettickcount-and-timegettime.aspx
448 // timeGetTime() provides 1ms granularity when combined with
449 // timeBeginPeriod(). If the host application for V8 wants fast timers, it
450 // can use timeBeginPeriod() to increase the resolution.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000451 // We use a lock-free version because the sampler thread calls it
452 // while having the rest of the world stopped, that could cause a deadlock.
453 base::Atomic32 rollover = base::Acquire_Load(&rollover_);
454 uint32_t now = static_cast<uint32_t>(timeGetTime());
455 if ((now >> 31) != static_cast<uint32_t>(rollover & 1)) {
456 base::Release_CompareAndSwap(&rollover_, rollover, rollover + 1);
457 ++rollover;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000458 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000459 uint64_t ms = (static_cast<uint64_t>(rollover) << 31) | now;
460 return static_cast<int64_t>(ms * Time::kMicrosecondsPerMillisecond);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000461 }
462
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000463 bool IsHighResolution() override { return false; }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000464
465 private:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000466 base::Atomic32 rollover_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000467};
468
469
470static LazyStaticInstance<RolloverProtectedTickClock,
471 DefaultConstructTrait<RolloverProtectedTickClock>,
472 ThreadSafeInitOnceTrait>::type tick_clock =
473 LAZY_STATIC_INSTANCE_INITIALIZER;
474
475
476struct CreateHighResTickClockTrait {
477 static TickClock* Create() {
478 // Check if the installed hardware supports a high-resolution performance
479 // counter, and if not fallback to the low-resolution tick clock.
480 LARGE_INTEGER ticks_per_second;
481 if (!QueryPerformanceFrequency(&ticks_per_second)) {
482 return tick_clock.Pointer();
483 }
484
485 // On Athlon X2 CPUs (e.g. model 15) the QueryPerformanceCounter
486 // is unreliable, fallback to the low-resolution tick clock.
487 CPU cpu;
488 if (strcmp(cpu.vendor(), "AuthenticAMD") == 0 && cpu.family() == 15) {
489 return tick_clock.Pointer();
490 }
491
492 return new HighResolutionTickClock(ticks_per_second.QuadPart);
493 }
494};
495
496
497static LazyDynamicInstance<TickClock, CreateHighResTickClockTrait,
498 ThreadSafeInitOnceTrait>::type high_res_tick_clock =
499 LAZY_DYNAMIC_INSTANCE_INITIALIZER;
500
501
502TimeTicks TimeTicks::Now() {
503 // Make sure we never return 0 here.
504 TimeTicks ticks(tick_clock.Pointer()->Now());
505 DCHECK(!ticks.IsNull());
506 return ticks;
507}
508
509
510TimeTicks TimeTicks::HighResolutionNow() {
511 // Make sure we never return 0 here.
512 TimeTicks ticks(high_res_tick_clock.Pointer()->Now());
513 DCHECK(!ticks.IsNull());
514 return ticks;
515}
516
517
518// static
519bool TimeTicks::IsHighResolutionClockWorking() {
520 return high_res_tick_clock.Pointer()->IsHighResolution();
521}
522
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000523#else // V8_OS_WIN
524
525TimeTicks TimeTicks::Now() {
526 return HighResolutionNow();
527}
528
529
530TimeTicks TimeTicks::HighResolutionNow() {
531 int64_t ticks;
532#if V8_OS_MACOSX
533 static struct mach_timebase_info info;
534 if (info.denom == 0) {
535 kern_return_t result = mach_timebase_info(&info);
536 DCHECK_EQ(KERN_SUCCESS, result);
537 USE(result);
538 }
539 ticks = (mach_absolute_time() / Time::kNanosecondsPerMicrosecond *
540 info.numer / info.denom);
541#elif V8_OS_SOLARIS
542 ticks = (gethrtime() / Time::kNanosecondsPerMicrosecond);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000543#elif V8_OS_POSIX
544 struct timespec ts;
545 int result = clock_gettime(CLOCK_MONOTONIC, &ts);
546 DCHECK_EQ(0, result);
547 USE(result);
548 ticks = (ts.tv_sec * Time::kMicrosecondsPerSecond +
549 ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
550#endif // V8_OS_MACOSX
551 // Make sure we never return 0 here.
552 return TimeTicks(ticks + 1);
553}
554
555
556// static
557bool TimeTicks::IsHighResolutionClockWorking() {
558 return true;
559}
560
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000561#endif // V8_OS_WIN
562
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000563} // namespace base
564} // namespace v8