All files / lib/internal/perf event_loop_utilization.js

100% Statements 60/60
100% Branches 11/11
100% Functions 2/2
100% Lines 60/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 6125x 25x 25x 25x 25x 25x 25x 25x 25x 25x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 25x 38x 38x 6x 6x 32x 37x 4x 4x 4x 4x 28x 28x 28x 28x 28x 28x 28x 37x 19x 19x 19x 19x 19x 19x 9x 9x 9x 9x 9x 9x 9x 9x 9x 38x 25x 25x 25x 25x 25x  
'use strict';
 
const {
  constants: {
    NODE_PERFORMANCE_MILESTONE_LOOP_START,
  },
  loopIdleTime,
  milestones,
} = internalBinding('performance');
 
function eventLoopUtilization(util1, util2) {
  // Get the original milestone timestamps that calculated from the beginning
  // of the process.
  return internalEventLoopUtilization(
    milestones[NODE_PERFORMANCE_MILESTONE_LOOP_START] / 1e6,
    loopIdleTime(),
    util1,
    util2
  );
}
 
function internalEventLoopUtilization(loopStart, loopIdleTime, util1, util2) {
  if (loopStart <= 0) {
    return { idle: 0, active: 0, utilization: 0 };
  }
 
  if (util2) {
    const idle = util1.idle - util2.idle;
    const active = util1.active - util2.active;
    return { idle, active, utilization: active / (idle + active) };
  }
 
  // Using process.hrtime() to get the time from the beginning of the process,
  // and offset it by the loopStart time (which is also calculated from the
  // beginning of the process).
  const now = process.hrtime();
  const active = now[0] * 1e3 + now[1] / 1e6 - loopStart - loopIdleTime;
 
  if (!util1) {
    return {
      idle: loopIdleTime,
      active,
      utilization: active / (loopIdleTime + active),
    };
  }
 
  const idleDelta = loopIdleTime - util1.idle;
  const activeDelta = active - util1.active;
  const utilization = activeDelta / (idleDelta + activeDelta);
  return {
    idle: idleDelta,
    active: activeDelta,
    utilization,
  };
}
 
module.exports = {
  internalEventLoopUtilization,
  eventLoopUtilization,
};