Skip to content

Commit

Permalink
src: fix negative values in process.hrtime()
Browse files Browse the repository at this point in the history
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: nodejs#4751
PR-URL: nodejs#4757
Reviewed-By: Evan Lucas <evanlucas@me.com>
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Reviewed-By: Сковорода Никита Андреевич <chalkerx@gmail.com>
  • Loading branch information
bnoordhuis authored and Michael Scovetta committed Apr 2, 2016
1 parent 028e811 commit 18a851e
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
7 changes: 3 additions & 4 deletions src/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
3 changes: 3 additions & 0 deletions test/parallel/test-process-hrtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 18a851e

Please sign in to comment.