问题描述
我有使用 hrtime
before = process.hrtime()
// stuff happens...
after = process.hrtime(before)
latency = (after[0] * 1000000000 + after[1]) / 1000000;
上面的latency
是什么单位?
解决方法
事实证明上面的实际上是毫秒。由于 setTimeout
以毫秒为单位获取延迟值,因此很容易验证我的 hrtime
杂耍:
const times = []
const delays = [1,10,100,1000,1001,1100];
function sleep(ms) {
return new Promise((res) => {
setTimeout(res,ms);
});
}
async function main() {
for (let ms of delays) {
const ping = process.hrtime();
await sleep(ms);
const pong = process.hrtime(ping);
const latency = (pong[0] * 1000000000 + pong[1]) / 1000000;
times.push(latency);
}
console.log(times);
// >>> [2.031091,11.623596,101.971041,1000.554953,1001.192077,1104.29338]
}
main();