Skip to content

Commit a2c257a

Browse files
bnoordhuisevanlucas
authored andcommitted
src: fix negative values in process.hrtime()
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: #4751 PR-URL: #4757 Reviewed-By: Evan Lucas <[email protected]> Reviewed-By: Trevor Norris <[email protected]> Reviewed-By: Сковорода Никита Андреевич <[email protected]>
1 parent fe23f42 commit a2c257a

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

src/node.js

+3-4
Original file line numberDiff line numberDiff line change
@@ -193,10 +193,9 @@
193193

194194
if (typeof ar !== 'undefined') {
195195
if (Array.isArray(ar)) {
196-
return [
197-
(hrValues[0] * 0x100000000 + hrValues[1]) - ar[0],
198-
hrValues[2] - ar[1]
199-
];
196+
const sec = (hrValues[0] * 0x100000000 + hrValues[1]) - ar[0];
197+
const nsec = hrValues[2] - ar[1];
198+
return [nsec < 0 ? sec - 1 : sec, nsec < 0 ? nsec + 1e9 : nsec];
200199
}
201200

202201
throw new TypeError('process.hrtime() only accepts an Array tuple');

test/parallel/test-process-hrtime.js

+3
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,6 @@ function validateTuple(tuple) {
2424
assert(isFinite(v));
2525
});
2626
}
27+
28+
const diff = process.hrtime([0, 1e9 - 1]);
29+
assert(diff[1] >= 0); // https://github.com/nodejs/node/issues/4751

0 commit comments

Comments
 (0)