process.hrtime([time])
process.hrtime.bigint()。- 'time' 整数[] 之前调用 'process.hrtime()' 的结果
- 返回值: 整数数组[]
这是 process.hrtime.bigint() 的旧版,在 JavaScript 引入 bigint 之前。
【This is the legacy version of process.hrtime.bigint()
before bigint was introduced in JavaScript.】
process.hrtime() 方法返回当前的高精度实时时间,结果为 [seconds, nanoseconds] 元组数组,其中 nanoseconds 是不能用秒精度表示的实时时间的剩余部分。
【The process.hrtime() method returns the current high-resolution real time
in a [seconds, nanoseconds] tuple Array, where nanoseconds is the
remaining part of the real time that can't be represented in second precision.】
time 是一个可选参数,必须是之前调用 process.hrtime() 的结果,用于与当前时间做差异计算。如果传入的参数不是一个元组 Array,将抛出 TypeError。传入用户自定义的数组而不是之前 process.hrtime() 调用的结果可能会导致未定义行为。
这些时间是相对于过去某一任意时间的,并不与一天中的时间相关,因此不会受到时钟漂移的影响。主要用途是在时间间隔之间测量性能:
【These times are relative to an arbitrary time in the past, and not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals:】
import { hrtime } from 'node:process';
const NS_PER_SEC = 1e9;
const time = hrtime();
// [ 1800216, 25 ]
setTimeout(() => {
const diff = hrtime(time);
// [ 1, 552 ]
console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
// Benchmark took 1000000552 nanoseconds
}, 1000);const { hrtime } = require('node:process');
const NS_PER_SEC = 1e9;
const time = hrtime();
// [ 1800216, 25 ]
setTimeout(() => {
const diff = hrtime(time);
// [ 1, 552 ]
console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
// Benchmark took 1000000552 nanoseconds
}, 1000);