From 1e5a02628c50f9a1fc6b214aa0926769c03b7dd1 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Tue, 19 Jan 2016 11:40:13 +0100 Subject: [PATCH] src: fix negative values in process.hrtime() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix a regression introduced in commit 89f056b ("node: improve performance of hrtime()") where the nanosecond field sometimes had a negative value when calculating the difference between two timestamps. Fixes: https://github.com/nodejs/node/issues/4751 PR-URL: https://github.com/nodejs/node/pull/4757 Reviewed-By: Evan Lucas Reviewed-By: Trevor Norris Reviewed-By: Сковорода Никита Андреевич --- src/node.js | 7 +++---- test/parallel/test-process-hrtime.js | 3 +++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/node.js b/src/node.js index 8e513a71c7c066..e28e4f7c320b37 100644 --- a/src/node.js +++ b/src/node.js @@ -193,10 +193,9 @@ if (typeof ar !== 'undefined') { if (Array.isArray(ar)) { - return [ - (hrValues[0] * 0x100000000 + hrValues[1]) - ar[0], - hrValues[2] - ar[1] - ]; + const sec = (hrValues[0] * 0x100000000 + hrValues[1]) - ar[0]; + const nsec = hrValues[2] - ar[1]; + return [nsec < 0 ? sec - 1 : sec, nsec < 0 ? nsec + 1e9 : nsec]; } throw new TypeError('process.hrtime() only accepts an Array tuple'); diff --git a/test/parallel/test-process-hrtime.js b/test/parallel/test-process-hrtime.js index ad186a3507d1e7..db16be0ad9e812 100644 --- a/test/parallel/test-process-hrtime.js +++ b/test/parallel/test-process-hrtime.js @@ -24,3 +24,6 @@ function validateTuple(tuple) { assert(isFinite(v)); }); } + +const diff = process.hrtime([0, 1e9 - 1]); +assert(diff[1] >= 0); // https://github.com/nodejs/node/issues/4751