4 回答

TA貢獻1735條經(jīng)驗 獲得超5個贊
您可以使用附加的os本機模塊來獲取有關(guān)您的 CPU 的信息來實現(xiàn)此目的:
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 都考慮在內(nèi)),你需要累加每個 CPU 的每次時間,而不僅僅是第一個,但在大多數(shù)情況下這應(yīng)該不太有用。
請注意,只有“系統(tǒng)”時間可以使用比第一個 CPU 多的時間,因為調(diào)用可以在與 NodeJS 核心分離的其他線程中運行。

TA貢獻1777條經(jīng)驗 獲得超3個贊
假設(shè)您在 linux/macos OS 下運行節(jié)點,另一種方法是:
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();
如果您的操作系統(tǒng)是 Windows,則您的命令必須不同。因為我沒有運行 Windows,所以我無法告訴你確切的命令,但你可以從這里開始:
您還可以檢查平臺process.platform
并執(zhí)行 if/else 語句,為特定操作系統(tǒng)設(shè)置正確的命令。

TA貢獻1998條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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
}
嘗試調(diào)整secNSec2ms function 以下內(nèi)容以檢查它是否解決了您的問題。
function secNSec2ms(secNSec) {
if (Array.isArray(secNSec))
return secNSec[0] * 1000 + secNSec[1] / 1000000 return secNSec / 1000;
}
添加回答
舉報