Skip to content

Commit 5b4f901

Browse files
author
Julien Gilli
committed
timers: Avoid linear scan in _unrefActive.
Before this change, _unrefActive would keep the unrefList sorted when adding a new timer. Because _unrefActive is called extremely frequently, this linear scan (O(n) at worse) would make _unrefActive show high in the list of contributors when profiling CPU usage. This commit changes _unrefActive so that it doesn't try to keep the unrefList sorted. The insertion thus happens in constant time. However, when a timer expires, unrefTimeout has to go through the whole unrefList because it's not ordered anymore. It is usually not large enough to have a significant impact on performance because: - Most of the time, the timers will be removed before unrefTimeout is called because their users (sockets mainly) cancel them when an I/O operation takes place. - If they're not, it means that some I/O took a long time to happen, and the initiator of subsequents I/O operations that would add more timers has to wait for them to complete. With this change, _unrefActive does not show as a significant contributor in CPU profiling reports anymore. Fixes nodejs#8160.
1 parent adf2cfd commit 5b4f901

File tree

2 files changed

+131
-54
lines changed

2 files changed

+131
-54
lines changed

lib/timers.js

+69-54
Original file line numberDiff line numberDiff line change
@@ -401,39 +401,78 @@ function unrefTimeout() {
401401

402402
debug('unrefTimer fired');
403403

404-
var first;
405-
while (first = L.peek(unrefList)) {
406-
var diff = now - first._monotonicStartTime;
404+
var timeSinceLastActive,
405+
nextTimeoutTime,
406+
nextTimeoutDuration,
407+
minNextTimeoutTime;
408+
409+
var itemToDelete;
410+
411+
// The actual timer fired and has not yet been rearmed,
412+
// let's consider its next firing time is invalid for now.
413+
// It may be set to a relevant time in the future once
414+
// we scanned through the whole list of timeouts and if
415+
// we find a timeout that needs to expire.
416+
unrefTimer.when = -1;
407417

408-
if (diff < first._idleTimeout) {
409-
diff = first._idleTimeout - diff;
410-
unrefTimer.start(diff, 0);
411-
unrefTimer.when = now + diff;
412-
debug('unrefTimer rescheudling for later');
413-
return;
414-
}
418+
// Iterate over the list of timeouts,
419+
// call the onTimeout callback for those expired,
420+
// and rearm the actual timer if the next timeout to expire
421+
// will expire before the current actual timer.
422+
var cur = unrefList._idlePrev;
423+
while (cur != unrefList) {
424+
timeSinceLastActive = now - cur._monotonicStartTime;
425+
426+
if (timeSinceLastActive < cur._idleTimeout) {
427+
nextTimeoutDuration = cur._idleTimeout - timeSinceLastActive;
428+
nextTimeoutTime = now + nextTimeoutDuration;
429+
if (minNextTimeoutTime == null ||
430+
(nextTimeoutTime < minNextTimeoutTime)) {
431+
// We found a timeout that will expire earlier,
432+
// store its next timeout time now so that we
433+
// can rearm the actual timer accordingly when
434+
// we scanned through the whole list.
435+
minNextTimeoutTime = nextTimeoutTime;
436+
}
415437

416-
L.remove(first);
438+
cur = cur._idlePrev;
439+
} else {
440+
try {
441+
var domain = cur.domain;
442+
if (!cur._onTimeout) continue;
443+
if (domain && domain._disposed) continue;
444+
if (domain) domain.enter();
417445

418-
var domain = first.domain;
446+
var threw = true;
419447

420-
if (!first._onTimeout) continue;
421-
if (domain && domain._disposed) continue;
448+
itemToDelete = cur;
449+
// Move to the previous item before calling the _onTimeout callback,
450+
// as it can mutate the list.
451+
cur = cur._idlePrev;
422452

423-
try {
424-
if (domain) domain.enter();
425-
var threw = true;
426-
debug('unreftimer firing timeout');
427-
first._onTimeout();
428-
threw = false;
429-
if (domain) domain.exit();
430-
} finally {
431-
if (threw) process.nextTick(unrefTimeout);
453+
// Remove the timeout from the list because it expired.
454+
L.remove(itemToDelete);
455+
456+
debug('unreftimer firing timeout');
457+
itemToDelete._onTimeout();
458+
459+
threw = false;
460+
461+
if (domain)
462+
domain.exit();
463+
} finally {
464+
if (threw) process.nextTick(unrefTimeout);
465+
}
432466
}
433467
}
434468

435-
debug('unrefList is empty');
436-
unrefTimer.when = -1;
469+
// Rearm the actual timer with the timeout delay
470+
// of the earliest timeout found.
471+
if (minNextTimeoutTime != null) {
472+
unrefTimer.start(minNextTimeoutTime - now, 0);
473+
unrefTimer.when = minNextTimeoutTime;
474+
debug('unrefTimer rescheduled');
475+
}
437476
}
438477

439478

@@ -462,38 +501,14 @@ exports._unrefActive = function(item) {
462501
item._idleStart = nowDate;
463502
item._monotonicStartTime = nowMonotonicTimestamp;
464503

465-
if (L.isEmpty(unrefList)) {
466-
debug('unrefList empty');
467-
L.append(unrefList, item);
504+
var when = nowMonotonicTimestamp + msecs;
468505

506+
// If the actual timer is set to fire too late, or not set to fire at all,
507+
// we need to make it fire earlier
508+
if (unrefTimer.when === -1 || unrefTimer.when > when) {
469509
unrefTimer.start(msecs, 0);
470-
unrefTimer.when = nowMonotonicTimestamp + msecs;
510+
unrefTimer.when = when;
471511
debug('unrefTimer scheduled');
472-
return;
473-
}
474-
475-
var when = nowMonotonicTimestamp + msecs;
476-
477-
debug('unrefList find where we can insert');
478-
479-
var cur, them;
480-
481-
for (cur = unrefList._idlePrev; cur != unrefList; cur = cur._idlePrev) {
482-
them = cur._monotonicStartTime + cur._idleTimeout;
483-
484-
if (when < them) {
485-
debug('unrefList inserting into middle of list');
486-
487-
L.append(cur, item);
488-
489-
if (unrefTimer.when > when) {
490-
debug('unrefTimer is scheduled to fire too late, reschedule');
491-
unrefTimer.start(msecs, 0);
492-
unrefTimer.when = when;
493-
}
494-
495-
return;
496-
}
497512
}
498513

499514
debug('unrefList append to end');
+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Copyright Joyent, Inc. and other Node contributors.
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a
4+
// copy of this software and associated documentation files (the
5+
// "Software"), to deal in the Software without restriction, including
6+
// without limitation the rights to use, copy, modify, merge, publish,
7+
// distribute, sublicense, and/or sell copies of the Software, and to permit
8+
// persons to whom the Software is furnished to do so, subject to the
9+
// following conditions:
10+
//
11+
// The above copyright notice and this permission notice shall be included
12+
// in all copies or substantial portions of the Software.
13+
//
14+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15+
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16+
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17+
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18+
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19+
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20+
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21+
22+
/*
23+
* This test is aimed at making sure that unref timers queued with
24+
* timers._unrefActive work correctly.
25+
*
26+
* Basically, it queues one timer in the unref queue, and then queues
27+
* it again each time its timeout callback is fired until the callback
28+
* has been called ten times.
29+
*
30+
* At that point, it unenrolls the unref timer so that its timeout callback
31+
* is not fired ever again.
32+
*
33+
* Finally, a ref timeout is used with a delay large enough to make sure that
34+
* all 10 timeouts had the time to expire.
35+
*/
36+
37+
var timers = require('timers');
38+
var assert = require('assert');
39+
40+
var someObject = {};
41+
var nbTimeouts = 0;
42+
43+
var N = 10;
44+
45+
timers.unenroll(someObject);
46+
timers.enroll(someObject, 1);
47+
48+
someObject._onTimeout = function _onTimeout() {
49+
++nbTimeouts;
50+
51+
if (nbTimeouts === N) timers.unenroll(someObject);
52+
53+
timers._unrefActive(someObject);
54+
}
55+
56+
function startTimer() { timers._unrefActive(someObject); }
57+
58+
startTimer();
59+
60+
setTimeout(function () {
61+
assert(nbTimeouts === N);
62+
}, 100);

0 commit comments

Comments
 (0)