Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(123)

Side by Side Diff: src/platform/time.cc

Issue 97073004: Make Time functions go through the Platform layer. (Closed) Base URL: git://github.com/v8/v8.git@bleeding_edge
Patch Set: Created 7 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/platform/default-platform-time.cc ('k') | tools/gyp/v8.gyp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2013 the V8 project authors. All rights reserved. 1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without 2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are 3 // modification, are permitted provided that the following conditions are
4 // met: 4 // met:
5 // 5 //
6 // * Redistributions of source code must retain the above copyright 6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer. 7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above 8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following 9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided 10 // disclaimer in the documentation and/or other materials provided
(...skipping 19 matching lines...) Expand all
30 #if V8_OS_POSIX 30 #if V8_OS_POSIX
31 #include <sys/time.h> 31 #include <sys/time.h>
32 #endif 32 #endif
33 #if V8_OS_MACOSX 33 #if V8_OS_MACOSX
34 #include <mach/mach_time.h> 34 #include <mach/mach_time.h>
35 #endif 35 #endif
36 36
37 #include <cstring> 37 #include <cstring>
38 38
39 #include "checks.h" 39 #include "checks.h"
40 #include "cpu.h"
41 #include "platform.h" 40 #include "platform.h"
41 #include "v8.h"
42 #if V8_OS_WIN 42 #if V8_OS_WIN
43 #include "win32-headers.h" 43 #include "win32-headers.h"
44 #endif 44 #endif
45 45
46 namespace v8 { 46 namespace v8 {
47 namespace internal { 47 namespace internal {
48 48
49 TimeDelta TimeDelta::FromDays(int days) { 49 TimeDelta TimeDelta::FromDays(int days) {
50 return TimeDelta(days * Time::kMicrosecondsPerDay); 50 return TimeDelta(days * Time::kMicrosecondsPerDay);
51 } 51 }
(...skipping 101 matching lines...) Expand 10 before | Expand all | Expand 10 after
153 struct timespec TimeDelta::ToTimespec() const { 153 struct timespec TimeDelta::ToTimespec() const {
154 struct timespec ts; 154 struct timespec ts;
155 ts.tv_sec = delta_ / Time::kMicrosecondsPerSecond; 155 ts.tv_sec = delta_ / Time::kMicrosecondsPerSecond;
156 ts.tv_nsec = (delta_ % Time::kMicrosecondsPerSecond) * 156 ts.tv_nsec = (delta_ % Time::kMicrosecondsPerSecond) *
157 Time::kNanosecondsPerMicrosecond; 157 Time::kNanosecondsPerMicrosecond;
158 return ts; 158 return ts;
159 } 159 }
160 160
161 #endif // V8_OS_POSIX 161 #endif // V8_OS_POSIX
162 162
163
164 #if V8_OS_WIN
165
166 // We implement time using the high-resolution timers so that we can get
167 // timeouts which are smaller than 10-15ms. To avoid any drift, we
168 // periodically resync the internal clock to the system clock.
169 class Clock V8_FINAL {
170 public:
171 Clock() : initial_ticks_(GetSystemTicks()), initial_time_(GetSystemTime()) {}
172
173 Time Now() {
174 // Time between resampling the un-granular clock for this API (1 minute).
175 const TimeDelta kMaxElapsedTime = TimeDelta::FromMinutes(1);
176
177 LockGuard<Mutex> lock_guard(&mutex_);
178
179 // Determine current time and ticks.
180 TimeTicks ticks = GetSystemTicks();
181 Time time = GetSystemTime();
182
183 // Check if we need to synchronize with the system clock due to a backwards
184 // time change or the amount of time elapsed.
185 TimeDelta elapsed = ticks - initial_ticks_;
186 if (time < initial_time_ || elapsed > kMaxElapsedTime) {
187 initial_ticks_ = ticks;
188 initial_time_ = time;
189 return time;
190 }
191
192 return initial_time_ + elapsed;
193 }
194
195 Time NowFromSystemTime() {
196 LockGuard<Mutex> lock_guard(&mutex_);
197 initial_ticks_ = GetSystemTicks();
198 initial_time_ = GetSystemTime();
199 return initial_time_;
200 }
201
202 private:
203 static TimeTicks GetSystemTicks() {
204 return TimeTicks::Now();
205 }
206
207 static Time GetSystemTime() {
208 FILETIME ft;
209 ::GetSystemTimeAsFileTime(&ft);
210 return Time::FromFiletime(ft);
211 }
212
213 TimeTicks initial_ticks_;
214 Time initial_time_;
215 Mutex mutex_;
216 };
217
218
219 static LazyStaticInstance<Clock,
220 DefaultConstructTrait<Clock>,
221 ThreadSafeInitOnceTrait>::type clock = LAZY_STATIC_INSTANCE_INITIALIZER;
222
223
224 Time Time::Now() { 163 Time Time::Now() {
225 return clock.Pointer()->Now(); 164 return Time(V8::GetCurrentPlatform()->CurrentTime());
226 } 165 }
227 166
228 167
229 Time Time::NowFromSystemTime() { 168 Time Time::NowFromSystemTime() {
230 return clock.Pointer()->NowFromSystemTime(); 169 return Time(V8::GetCurrentPlatform()->CurrentTimeFromSystemTime());
231 } 170 }
232 171
172 #if V8_OS_WIN
233 173
234 // Time between windows epoch and standard epoch. 174 // Time between windows epoch and standard epoch.
235 static const int64_t kTimeToEpochInMicroseconds = V8_INT64_C(11644473600000000); 175 static const int64_t kTimeToEpochInMicroseconds = V8_INT64_C(11644473600000000);
236 176
237 177
238 Time Time::FromFiletime(FILETIME ft) { 178 Time Time::FromFiletime(FILETIME ft) {
239 if (ft.dwLowDateTime == 0 && ft.dwHighDateTime == 0) { 179 if (ft.dwLowDateTime == 0 && ft.dwHighDateTime == 0) {
240 return Time(); 180 return Time();
241 } 181 }
242 if (ft.dwLowDateTime == std::numeric_limits<DWORD>::max() && 182 if (ft.dwLowDateTime == std::numeric_limits<DWORD>::max() &&
(...skipping 20 matching lines...) Expand all
263 return ft; 203 return ft;
264 } 204 }
265 uint64_t us = static_cast<uint64_t>(us_ + kTimeToEpochInMicroseconds) * 10; 205 uint64_t us = static_cast<uint64_t>(us_ + kTimeToEpochInMicroseconds) * 10;
266 ft.dwLowDateTime = static_cast<DWORD>(us); 206 ft.dwLowDateTime = static_cast<DWORD>(us);
267 ft.dwHighDateTime = static_cast<DWORD>(us >> 32); 207 ft.dwHighDateTime = static_cast<DWORD>(us >> 32);
268 return ft; 208 return ft;
269 } 209 }
270 210
271 #elif V8_OS_POSIX 211 #elif V8_OS_POSIX
272 212
273 Time Time::Now() {
274 struct timeval tv;
275 int result = gettimeofday(&tv, NULL);
276 ASSERT_EQ(0, result);
277 USE(result);
278 return FromTimeval(tv);
279 }
280
281
282 Time Time::NowFromSystemTime() {
283 return Now();
284 }
285
286
287 Time Time::FromTimespec(struct timespec ts) { 213 Time Time::FromTimespec(struct timespec ts) {
288 ASSERT(ts.tv_nsec >= 0); 214 ASSERT(ts.tv_nsec >= 0);
289 ASSERT(ts.tv_nsec < static_cast<long>(kNanosecondsPerSecond)); // NOLINT 215 ASSERT(ts.tv_nsec < static_cast<long>(kNanosecondsPerSecond)); // NOLINT
290 if (ts.tv_nsec == 0 && ts.tv_sec == 0) { 216 if (ts.tv_nsec == 0 && ts.tv_sec == 0) {
291 return Time(); 217 return Time();
292 } 218 }
293 if (ts.tv_nsec == static_cast<long>(kNanosecondsPerSecond - 1) && // NOLINT 219 if (ts.tv_nsec == static_cast<long>(kNanosecondsPerSecond - 1) && // NOLINT
294 ts.tv_sec == std::numeric_limits<time_t>::max()) { 220 ts.tv_sec == std::numeric_limits<time_t>::max()) {
295 return Max(); 221 return Max();
296 } 222 }
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
368 return 0; 294 return 0;
369 } 295 }
370 if (IsMax()) { 296 if (IsMax()) {
371 // Preserve max without offset to prevent overflow. 297 // Preserve max without offset to prevent overflow.
372 return std::numeric_limits<double>::max(); 298 return std::numeric_limits<double>::max();
373 } 299 }
374 return static_cast<double>(us_) / kMicrosecondsPerMillisecond; 300 return static_cast<double>(us_) / kMicrosecondsPerMillisecond;
375 } 301 }
376 302
377 303
378 #if V8_OS_WIN
379
380 class TickClock {
381 public:
382 virtual ~TickClock() {}
383 virtual int64_t Now() = 0;
384 virtual bool IsHighResolution() = 0;
385 };
386
387
388 // Overview of time counters:
389 // (1) CPU cycle counter. (Retrieved via RDTSC)
390 // The CPU counter provides the highest resolution time stamp and is the least
391 // expensive to retrieve. However, the CPU counter is unreliable and should not
392 // be used in production. Its biggest issue is that it is per processor and it
393 // is not synchronized between processors. Also, on some computers, the counters
394 // will change frequency due to thermal and power changes, and stop in some
395 // states.
396 //
397 // (2) QueryPerformanceCounter (QPC). The QPC counter provides a high-
398 // resolution (100 nanoseconds) time stamp but is comparatively more expensive
399 // to retrieve. What QueryPerformanceCounter actually does is up to the HAL.
400 // (with some help from ACPI).
401 // According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx
402 // in the worst case, it gets the counter from the rollover interrupt on the
403 // programmable interrupt timer. In best cases, the HAL may conclude that the
404 // RDTSC counter runs at a constant frequency, then it uses that instead. On
405 // multiprocessor machines, it will try to verify the values returned from
406 // RDTSC on each processor are consistent with each other, and apply a handful
407 // of workarounds for known buggy hardware. In other words, QPC is supposed to
408 // give consistent result on a multiprocessor computer, but it is unreliable in
409 // reality due to bugs in BIOS or HAL on some, especially old computers.
410 // With recent updates on HAL and newer BIOS, QPC is getting more reliable but
411 // it should be used with caution.
412 //
413 // (3) System time. The system time provides a low-resolution (typically 10ms
414 // to 55 milliseconds) time stamp but is comparatively less expensive to
415 // retrieve and more reliable.
416 class HighResolutionTickClock V8_FINAL : public TickClock {
417 public:
418 explicit HighResolutionTickClock(int64_t ticks_per_second)
419 : ticks_per_second_(ticks_per_second) {
420 ASSERT_LT(0, ticks_per_second);
421 }
422 virtual ~HighResolutionTickClock() {}
423
424 virtual int64_t Now() V8_OVERRIDE {
425 LARGE_INTEGER now;
426 BOOL result = QueryPerformanceCounter(&now);
427 ASSERT(result);
428 USE(result);
429
430 // Intentionally calculate microseconds in a round about manner to avoid
431 // overflow and precision issues. Think twice before simplifying!
432 int64_t whole_seconds = now.QuadPart / ticks_per_second_;
433 int64_t leftover_ticks = now.QuadPart % ticks_per_second_;
434 int64_t ticks = (whole_seconds * Time::kMicrosecondsPerSecond) +
435 ((leftover_ticks * Time::kMicrosecondsPerSecond) / ticks_per_second_);
436
437 // Make sure we never return 0 here, so that TimeTicks::HighResolutionNow()
438 // will never return 0.
439 return ticks + 1;
440 }
441
442 virtual bool IsHighResolution() V8_OVERRIDE {
443 return true;
444 }
445
446 private:
447 int64_t ticks_per_second_;
448 };
449
450
451 class RolloverProtectedTickClock V8_FINAL : public TickClock {
452 public:
453 // We initialize rollover_ms_ to 1 to ensure that we will never
454 // return 0 from TimeTicks::HighResolutionNow() and TimeTicks::Now() below.
455 RolloverProtectedTickClock() : last_seen_now_(0), rollover_ms_(1) {}
456 virtual ~RolloverProtectedTickClock() {}
457
458 virtual int64_t Now() V8_OVERRIDE {
459 LockGuard<Mutex> lock_guard(&mutex_);
460 // We use timeGetTime() to implement TimeTicks::Now(), which rolls over
461 // every ~49.7 days. We try to track rollover ourselves, which works if
462 // TimeTicks::Now() is called at least every 49 days.
463 // Note that we do not use GetTickCount() here, since timeGetTime() gives
464 // more predictable delta values, as described here:
465 // http://blogs.msdn.com/b/larryosterman/archive/2009/09/02/what-s-the-diffe rence-between-gettickcount-and-timegettime.aspx
466 // timeGetTime() provides 1ms granularity when combined with
467 // timeBeginPeriod(). If the host application for V8 wants fast timers, it
468 // can use timeBeginPeriod() to increase the resolution.
469 DWORD now = timeGetTime();
470 if (now < last_seen_now_) {
471 rollover_ms_ += V8_INT64_C(0x100000000); // ~49.7 days.
472 }
473 last_seen_now_ = now;
474 return (now + rollover_ms_) * Time::kMicrosecondsPerMillisecond;
475 }
476
477 virtual bool IsHighResolution() V8_OVERRIDE {
478 return false;
479 }
480
481 private:
482 Mutex mutex_;
483 DWORD last_seen_now_;
484 int64_t rollover_ms_;
485 };
486
487
488 static LazyStaticInstance<RolloverProtectedTickClock,
489 DefaultConstructTrait<RolloverProtectedTickClock>,
490 ThreadSafeInitOnceTrait>::type tick_clock =
491 LAZY_STATIC_INSTANCE_INITIALIZER;
492
493
494 struct CreateHighResTickClockTrait {
495 static TickClock* Create() {
496 // Check if the installed hardware supports a high-resolution performance
497 // counter, and if not fallback to the low-resolution tick clock.
498 LARGE_INTEGER ticks_per_second;
499 if (!QueryPerformanceFrequency(&ticks_per_second)) {
500 return tick_clock.Pointer();
501 }
502
503 // On Athlon X2 CPUs (e.g. model 15) the QueryPerformanceCounter
504 // is unreliable, fallback to the low-resolution tick clock.
505 CPU cpu;
506 if (strcmp(cpu.vendor(), "AuthenticAMD") == 0 && cpu.family() == 15) {
507 return tick_clock.Pointer();
508 }
509
510 return new HighResolutionTickClock(ticks_per_second.QuadPart);
511 }
512 };
513
514
515 static LazyDynamicInstance<TickClock,
516 CreateHighResTickClockTrait,
517 ThreadSafeInitOnceTrait>::type high_res_tick_clock =
518 LAZY_DYNAMIC_INSTANCE_INITIALIZER;
519
520
521 TimeTicks TimeTicks::Now() { 304 TimeTicks TimeTicks::Now() {
305 TimeTicks ticks = TimeTicks(i::V8::GetCurrentPlatform()->TimeTicksNow());
522 // Make sure we never return 0 here. 306 // Make sure we never return 0 here.
523 TimeTicks ticks(tick_clock.Pointer()->Now());
524 ASSERT(!ticks.IsNull()); 307 ASSERT(!ticks.IsNull());
525 return ticks; 308 return ticks;
526 } 309 }
527 310
528 311
529 TimeTicks TimeTicks::HighResolutionNow() { 312 TimeTicks TimeTicks::HighResolutionNow() {
313 TimeTicks ticks = TimeTicks(
314 i::V8::GetCurrentPlatform()->TimeTicksHighResNow());
530 // Make sure we never return 0 here. 315 // Make sure we never return 0 here.
531 TimeTicks ticks(high_res_tick_clock.Pointer()->Now());
532 ASSERT(!ticks.IsNull()); 316 ASSERT(!ticks.IsNull());
533 return ticks; 317 return ticks;
534 } 318 }
535 319
536 320
537 // static 321 // static
538 bool TimeTicks::IsHighResolutionClockWorking() { 322 bool TimeTicks::IsHighResolutionClockWorking() {
539 return high_res_tick_clock.Pointer()->IsHighResolution(); 323 return i::V8::GetCurrentPlatform()->TimeTicksHasHighRes();
540 } 324 }
541 325
542 #else // V8_OS_WIN
543
544 TimeTicks TimeTicks::Now() {
545 return HighResolutionNow();
546 }
547
548
549 TimeTicks TimeTicks::HighResolutionNow() {
550 int64_t ticks;
551 #if V8_OS_MACOSX
552 static struct mach_timebase_info info;
553 if (info.denom == 0) {
554 kern_return_t result = mach_timebase_info(&info);
555 ASSERT_EQ(KERN_SUCCESS, result);
556 USE(result);
557 }
558 ticks = (mach_absolute_time() / Time::kNanosecondsPerMicrosecond *
559 info.numer / info.denom);
560 #elif V8_OS_SOLARIS
561 ticks = (gethrtime() / Time::kNanosecondsPerMicrosecond);
562 #elif V8_LIBRT_NOT_AVAILABLE
563 // TODO(bmeurer): This is a temporary hack to support cross-compiling
564 // Chrome for Android in AOSP. Remove this once AOSP is fixed, also
565 // cleanup the tools/gyp/v8.gyp file.
566 struct timeval tv;
567 int result = gettimeofday(&tv, NULL);
568 ASSERT_EQ(0, result);
569 USE(result);
570 ticks = (tv.tv_sec * Time::kMicrosecondsPerSecond + tv.tv_usec);
571 #elif V8_OS_POSIX
572 struct timespec ts;
573 int result = clock_gettime(CLOCK_MONOTONIC, &ts);
574 ASSERT_EQ(0, result);
575 USE(result);
576 ticks = (ts.tv_sec * Time::kMicrosecondsPerSecond +
577 ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
578 #endif // V8_OS_MACOSX
579 // Make sure we never return 0 here.
580 return TimeTicks(ticks + 1);
581 }
582
583
584 // static
585 bool TimeTicks::IsHighResolutionClockWorking() {
586 return true;
587 }
588
589 #endif // V8_OS_WIN
590
591 } } // namespace v8::internal 326 } } // namespace v8::internal
OLDNEW
« no previous file with comments | « src/platform/default-platform-time.cc ('k') | tools/gyp/v8.gyp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698