process.cpuUsage([previousValue])
process.cpuUsage()
方法在具有属性 user
和 system
的对象中返回当前进程的用户和系统 CPU 时间使用情况,其值为微秒值(百万分之一秒)。
这些值分别测量在用户和系统代码中花费的时间,如果多个 CPU 内核为此进程执行工作,则最终可能会大于实际经过的时间。
先前调用 process.cpuUsage()
的结果可以作为参数传给函数,以获取差异读数。
import { cpuUsage } from 'node:process';
const startUsage = cpuUsage();
// { user: 38579, system: 6986 }
// 使 CPU 旋转 500 毫秒
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 }
// 使 CPU 旋转 500 毫秒
const now = Date.now();
while (Date.now() - now < 500);
console.log(cpuUsage(startUsage));
// { user: 514883, system: 11226 }
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.
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 }