0

I'm trying to calculate the normalized cpu percentage for my node process. My goal is to get it to match the output that I have in my htop for the pid but I'm unable to do so. My code is below along with my htop output.

import { cpuUsage } from "node:process";
import { cpus } from "os";

function basicCpuUsage() {
  const startTime = process.hrtime();
  const startUsage = cpuUsage();
  const numCpus = cpus().length;

  const add = 1 + 1; // make cpu do work?

  const usageDiff = cpuUsage(startUsage); // get diff time from start
  const endTime = process.hrtime(startTime); // total amount of time that has elapsed
  const usageMS = (usageDiff.user + usageDiff.system) / 1e3;
  const totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;

  const cpuPercent = (usageMS / totalMS) * 100;
  const normTotal = usageMS / numCpus; // average usage time per cpu
  const normPercent = (normTotal / totalMS) * 100;

  console.log({
    cpuPercent: cpuPercent.toFixed(2),
    normPercent: normPercent.toFixed(2),
  });
}

process.title = "CPU Test";
const { pid } = process;
console.log({ pid });
const title = setInterval(() => {
  basicCpuUsage();
}, 1000);

Here is my output, as you can see my code cpu output does no match my htop cpu output. Which part of my calculation is incorrect? I was thinking this might have to do with my setInterval function call, but not sure. I am attempting to create a long running process where I can view the cpu usage.

htop output

pythonNovice
  • 1,130
  • 1
  • 14
  • 36

1 Answers1

0

Turns out I was making an incorrect calculation. I was dividing my totalTimeMS twice when I should have done it once. Additionally I moved the currentUsage and currentTime to the outside of the function.

Below is the correct calculation:

import { cpus } from "os";

let currentUsage = process.cpuUsage();
let currentTime = process.hrtime();

function basicCpuUsage() {
  const numCpus = cpus().length;

  const usageDiff = process.cpuUsage(currentUsage); // get diff time from start
  const endTime = process.hrtime(currentTime); // total amount of time that has elapsed

  currentUsage = process.cpuUsage()
  currentTime = process.hrtime();

  const usageMS = (usageDiff.user + usageDiff.system) / 1e3;
  const totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;

  const cpuPercent = (usageMS / totalMS) * 100;
  const normPercent = (usageMS / totalMS / numCpus) * 100; // average usage time per cpu

  console.log({
    cpuPercent: cpuPercent.toFixed(2),
    normPercent: normPercent.toFixed(2),
  });
}

process.title = "CPU Test";

setInterval(() => {
 for (let i = 0; i < 25; i++) {
    const add = 1 + 1;
  }
  basicCpuUsage();
}, 5000);

cpu usage

pythonNovice
  • 1,130
  • 1
  • 14
  • 36