process.cpuUsage([previousValue])


process.cpuUsage() 方法返回当前进程的用户和系统 CPU 使用时间,以包含 usersystem 属性的对象形式表示,其值为微秒(百万分之一秒)。这些值分别衡量在用户代码和系统代码中花费的时间,如果多个 CPU 核心同时为该进程工作,这些值可能会大于实际经过的时间。

【The process.cpuUsage() method returns the user and system CPU time usage of the current process, in an object with properties user and system, whose values are microsecond values (millionth of a second). These values measure time spent in user and system code respectively, and may end up being greater than actual elapsed time if multiple CPU cores are performing work for this process.】

之前对 process.cpuUsage() 的调用结果可以作为参数传递给该函数,以获取差异读取值。

【The result of a previous call to process.cpuUsage() can be passed as the argument to the function, to get a diff reading.】

import { cpuUsage } from 'node:process';

const startUsage = cpuUsage();
// { user: 38579, system: 6986 }

// spin the CPU for 500 milliseconds
const now = Date.now();
while (Date.now() - now < 500);

console.log(cpuUsage(startUsage));
// { user: 514883, system: 11226 }const { cpuUsage } = require('node:process');

const startUsage = cpuUsage();
// { user: 38579, system: 6986 }

// spin the CPU for 500 milliseconds
const now = Date.now();
while (Date.now() - now < 500);

console.log(cpuUsage(startUsage));
// { user: 514883, system: 11226 }