📜  Node.js process.cpuUsage() 方法

📅  最后修改于: 2022-05-13 01:56:32.790000             🧑  作者: Mango

Node.js process.cpuUsage() 方法

process.cpuUsage() 方法是 Process 模块的一个内置应用程序编程接口,用于获取当前进程的用户、系统 CPU 时间使用情况。它作为具有属性 user 和 system 的对象返回,值以微秒为单位。返回值可能与实际经过的时间不同,尤其是对于多核 CPU。

句法:

process.cpuUsage( previous_value )

参数:此方法接受如上所述和如下所述的单个参数:

  • previous_value:可选参数,之前调用process.cpuUsage()返回的对象。如果通过,则返回差值。

返回:此方法在成功时返回一个对象,其中包含用户和系统等属性,并带有一些整数值,表示进程经过的时间,以微秒为单位。

  • user:是一个整数,表示用户经过的时间
  • system:是一个整数,表示系统经过的时间

下面的例子说明了在 Node.js 中process.cpuUsage() 方法的使用:

示例 1:

Javascript
// Allocating process module
const process = require('process');
  
// Calling process.cpuUsage() method
const usage = process.cpuUsage();
  
// Printing returned value
console.log(usage);


Javascript
// Allocating process module
const process = require('process');
  
// Calling process.cpuUsage() method
var usage = process.cpuUsage();
// Printing returned value
console.log("cpu usage before: ", usage);
  
// Current time
const now = Date.now();
  
// Loop to delay almost 100 milliseconds
while (Date.now() - now < 100);
  
// After using the cpu for nearly equal to 
// 100 milliseconds
// Calling process.cpuUsage() method
usage = process.cpuUsage(usage);
  
// Printing returned value
console.log("Cpu usage by this process: ", usage);


输出:

{ user: 78000, system: 15000 }

示例 2:

Javascript

// Allocating process module
const process = require('process');
  
// Calling process.cpuUsage() method
var usage = process.cpuUsage();
// Printing returned value
console.log("cpu usage before: ", usage);
  
// Current time
const now = Date.now();
  
// Loop to delay almost 100 milliseconds
while (Date.now() - now < 100);
  
// After using the cpu for nearly equal to 
// 100 milliseconds
// Calling process.cpuUsage() method
usage = process.cpuUsage(usage);
  
// Printing returned value
console.log("Cpu usage by this process: ", usage);

输出:

cpu usage before:  { user: 62000, system: 15000 }
Cpu usage by this process:  { user: 109000, system: 0 }

参考: https://nodejs.org/api/process.html#process_process_cpuusage_previousvalue