Skip to content

Commit 0b11585

Browse files
Fix issue with previous_now comparison
uv_hrtime() can return a value that is greater than the max possible uint32 value. Promote previous_now to uint64 to do fair comparisons. Switch to uint32 only when computing duration. Co-authored-by: Cameron Gorrie <[email protected]>
1 parent c8bfec1 commit 0b11585

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

src/eventLoopStats.cc

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
using namespace v8;
44

5-
const uint32_t maxPossibleNumber = 4294967295;
6-
const uint32_t minPossibleNumber = 0;
5+
// Casting -1 to an uint will give the max uint value
6+
const uint32_t maxPossibleUint32 = -1;
7+
const uint64_t maxPossibleUint64 = -1;
8+
const uint32_t minPossibleUint32 = 0;
79

810
uv_check_t check_handle;
911

@@ -16,12 +18,12 @@ uint32_t sum;
1618
// The number of event loop iterations since the last sense() call.
1719
uint32_t num;
1820

19-
uint32_t previous_now = maxPossibleNumber;
21+
uint64_t previous_now = maxPossibleUint64;
2022

2123
// This will be called after each sense call.
2224
void reset() {
23-
min = maxPossibleNumber;
24-
max = minPossibleNumber;
25+
min = maxPossibleUint32;
26+
max = minPossibleUint32;
2527
sum = 0;
2628
num = 0;
2729
}
@@ -36,9 +38,9 @@ void on_check(uv_check_t* handle) {
3638
// long running for- or while-loops. Checking against the time of the same
3739
// point at the last iteration of the event loop also covers these cases.
3840

39-
// Convert the timestamp to milliseconds (uv_hrtime yields nanos).
40-
const uint64_t now = uv_hrtime() / static_cast<uint64_t>(1e6);
41-
uint64_t duration;
41+
const uint64_t now = uv_hrtime();
42+
uint32_t duration;
43+
4244
if (previous_now >= now) {
4345
// This only happens on the very first call on_check call. Since we have no
4446
// timestamp to compare to from an earlier on_check call, we start by
@@ -47,10 +49,10 @@ void on_check(uv_check_t* handle) {
4749
} else {
4850
// Calculate the duration since the last on_check call - this is the
4951
// event loop lag.
50-
duration = now - previous_now;
52+
// And convert to milliseconds (uv_hrtime yields nanos).
53+
duration = (now - previous_now) / static_cast<uint64_t>(1e6);
5154
}
5255

53-
5456
// save min/max values
5557
if (duration < min) {
5658
min = duration;

0 commit comments

Comments
 (0)