Ale*_*lex 10 javascript process cpu-usage percentage node.js
该process.cpuUsage()函数显示一些奇怪的微秒值。如何以百分比获取cpu使用率?
假设您在 linux/macos 操作系统下运行节点,另一种选择是:
var exec = require("child_process").exec;
function getProcessPercent() {
// GET current node process id.
const pid = process.pid;
console.log(pid);
//linux command to get cpu percentage for the specific Process Id.
var cmd = `ps up "${pid}" | tail -n1 | tr -s ' ' | cut -f3 -d' '`;
setInterval(() => {
//executes the command and returns the percentage value
exec(cmd, function (err, percentValue) {
if (err) {
console.log("Command `ps` returned an error!");
} else {
console.log(`${percentValue* 1}%`);
}
});
}, 1000);
}
getProcessPercent();
Run Code Online (Sandbox Code Playgroud)
如果您的操作系统是 Windows,则您的命令必须不同。由于我没有运行 Windows,我无法告诉您确切的命令,但您可以从这里开始:
您还可以使用 if/else 语句检查平台process.platform并为特定操作系统设置正确的命令。
您可以使用附加os本机模块获取有关 CPU 的信息来实现此目的:
const os = require('os');
// Take the first CPU, considering every CPUs have the same specs
// and every NodeJS process only uses one at a time.
const cpus = os.cpus();
const cpu = cpus[0];
// Accumulate every CPU times values
const total = Object.values(cpu.times).reduce(
(acc, tv) => acc + tv, 0
);
// Normalize the one returned by process.cpuUsage()
// (microseconds VS miliseconds)
const usage = process.cpuUsage();
const currentCPUUsage = (usage.user + usage.system) * 1000;
// Find out the percentage used for this specific CPU
const perc = currentCPUUsage / total * 100;
console.log(`CPU Usage (%): ${perc}`);
Run Code Online (Sandbox Code Playgroud)
如果您想获得全局 CPU 使用率(考虑所有 CPU),您需要累积每个 CPU 的每次使用次数,不仅是第一个,但在大多数情况下这应该不太有用。
请注意,只有“系统”时间可以使用比第一个 CPU 多的时间,因为调用可以在与 NodeJS 核心分离的其他线程中运行。
来源:
在回答之前,我们需要先了解几个事实:
process.cpuUsage是 Node.js 进程使用的所有 CPU 的累积时间因此,要考虑主机的所有 CPU 来计算 Node.js 的 CPU 使用率,我们可以使用类似以下内容的方法:
const ncpu = require("os").cpus().length;
let previousTime = new Date().getTime();
let previousUsage = process.cpuUsage();
let lastUsage;
setInterval(() => {
const currentUsage = process.cpuUsage(previousUsage);
previousUsage = process.cpuUsage();
// we can't do simply times / 10000 / ncpu because we can't trust
// setInterval is executed exactly every 1.000.000 microseconds
const currentTime = new Date().getTime();
// times from process.cpuUsage are in microseconds while delta time in milliseconds
// * 10 to have the value in percentage for only one cpu
// * ncpu to have the percentage for all cpus af the host
// this should match top's %CPU
const timeDelta = (currentTime - previousTime) * 10;
// this would take care of CPUs number of the host
// const timeDelta = (currentTime - previousTime) * 10 * ncpu;
const { user, system } = currentUsage;
lastUsage = { system: system / timeDelta, total: (system + user) / timeDelta, user: user / timeDelta };
previousTime = currentTime;
console.log(lastUsage);
}, 1000);
Run Code Online (Sandbox Code Playgroud)
或者我们可以从需要的地方读取它的值,lastUsage而不是将其打印到控制台。