简体   繁体   English

如何正确获取有关 CPU 使用率的信息?

[英]How to get properly information about CPU usage?

I want to get a few metrics from my NodeJS app like cpuUsage for user, system and as total usage.我想从我的cpuUsage应用程序中获取一些指标,例如用户、系统的 cpuUsage 和总使用量。 Below is my simple code:下面是我的简单代码:

private lastCpuUsage = process.cpuUsage();

getCpuUsage() {
    const cpuUsage = process.cpuUsage();

    const userUsageMicros = cpuUsage.user - this.lastCpuUsage.user;
    const systemUsageMicros = cpuUsage.system - this.lastCpuUsage.system;

    this.lastCpuUsage = cpuUsage;

    console.log({
      cpuUserUsage: userUsageMicros / 1e6, //1000000
      cpuSystemUsage: systemUsageMicros / 1e6,
      cpuTotalUsage: (userUsageMicros + systemUsageMicros) / 1e6
    })
}

and here is a sample output:这是一个示例 output:

{
    "cpuUserUsage": 0.016,
    "cpuSystemUsage": 0.031,
    "cpuTotalUsage": 0.047
}

And now I've got two questions:现在我有两个问题:

  1. How to get cpuUsage in percentage unit?如何以百分比为单位获取cpuUsage?
  2. This output is for the entire machine on which my application stands or only for a specific application from which I download this data?这个 output 是针对我的应用程序所在的整台机器还是仅针对我从中下载此数据的特定应用程序? And if is only for my app, how can I get data from the entire system?如果仅针对我的应用程序,我如何从整个系统获取数据?

Thanks for any help!谢谢你的帮助!

If all the CPUs are in the same spec and processes are using only one CPU, then try with os module.如果所有 CPU 都在同一规格中,并且进程只使用一个 CPU,则尝试使用os模块。 Node OS节点操作系统

const os = require('os');

const [cpu] = os.cpus();

const total = Object.values(cpu.times).reduce(
    (acc, val) => acc + val, 0
);

const { user, system } = process.cpuUsage();
const percentage = 100 * 1000 * (user + system) / total ;

console.log(percentage);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM