4 回答
TA贡献1735条经验 获得超5个赞
您可以使用附加的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}`);
如果你想获得全局 CPU 使用率(将你所有的 CPU 都考虑在内),你需要累加每个 CPU 的每次时间,而不仅仅是第一个,但在大多数情况下这应该不太有用。
请注意,只有“系统”时间可以使用比第一个 CPU 多的时间,因为调用可以在与 NodeJS 核心分离的其他线程中运行。
TA贡献1777条经验 获得超3个赞
假设您在 linux/macos OS 下运行节点,另一种方法是:
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();
如果您的操作系统是 Windows,则您的命令必须不同。因为我没有运行 Windows,所以我无法告诉你确切的命令,但你可以从这里开始:
您还可以检查平台process.platform并执行 if/else 语句,为特定操作系统设置正确的命令。
TA贡献1998条经验 获得超6个赞
在回答之前,我们需要注意几个事实:
Node.js 并不是只使用一个 CPU,而是每个异步 I/O 操作都可能使用额外的 CPU
返回的时间
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);
或者我们可以lastUsage从我们需要的地方读取它的值,而不是将它打印到控制台。
TA贡献1719条经验 获得超6个赞
尝试使用以下代码获取 % 的 cpu 使用率
var startTime = process.hrtime()
var startUsage = process.cpuUsage()
// spin the CPU for 500 milliseconds
var now = Date.now()
while (Date.now() - now < 500)
var elapTime = process.hrtime(startTime)
var elapUsage = process.cpuUsage(startUsage)
var elapTimeMS = secNSec2ms(elapTime)
var elapUserMS = secNSec2ms(elapUsage.user)
var elapSystMS = secNSec2ms(elapUsage.system)
var cpuPercent = Math.round(100 * (elapUserMS + elapSystMS) / elapTimeMS)
console.log('elapsed time ms: ', elapTimeMS)
console.log('elapsed user ms: ', elapUserMS)
console.log('elapsed system ms:', elapSystMS)
console.log('cpu percent: ', cpuPercent)
function secNSec2ms (secNSec) {
return secNSec[0] * 1000 + secNSec[1] / 1000000
}
尝试调整secNSec2ms function 以下内容以检查它是否解决了您的问题。
function secNSec2ms(secNSec) {
if (Array.isArray(secNSec))
return secNSec[0] * 1000 + secNSec[1] / 1000000 return secNSec / 1000;
}
添加回答
举报
