簡體   English   中英

嘗試獲取節點進程的標准化 CPU 使用率

[英]Trying to get normalized CPU usage for node process

我正在嘗試計算我的節點進程的標准化 cpu 百分比。 我的目標是讓它與我在htop中的 pid 輸出相匹配,但我無法這樣做。 下面是我的代碼以及我的 htop 輸出。

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);

這是我的輸出,您可以看到我的代碼 cpu 輸出與我的 htop cpu 輸出不匹配。 我的計算哪一部分不正確? 我在想這可能與我的setInterval函數調用有關,但不確定。 我正在嘗試創建一個長時間運行的進程,我可以在其中查看 cpu 使用情況。

頂層輸出

結果我計算錯了。 當我應該做一次時,我將我的totalTimeMS划分了兩次。 此外,我將 currentUsage 和 currentTime 移到了函數的外部。

下面是正確的計算:

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使用率

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM