在Node.js中单调增加时间

Luc*_*iva 8 javascript node.js system-clock

这个问题已经回答为Javascript 这里,但window.performance.now()显然是不提供Node.js的

某些应用需要一个稳定的时钟,即一个随时间单调增加的时钟,不受系统时钟漂移的影响.例如,Java有System.nanoTime()和C++有std::chrono::steady_clock.Node.js中有这样的时钟吗?

Luc*_*iva 9

结果是Node.js中的等价物process.hrtime().根据文件:

[process.hrtime()返回的时间相对于过去的任意时间而言,与时间无关,因此不受时钟漂移的影响.


假设我们希望每秒定期调用一次REST端点,处理其结果并将某些内容打印到日志文件中.考虑端点可能需要一段时间来响应,例如,从几百毫秒到多于一秒.我们不希望有两个并发请求,因此setInterval()不能完全满足我们的需求.

一个好的方法是第一次调用我们的函数,执行请求,处理它然后调用setTimeout()并重新安排进行另一次运行.但考虑到我们花在请求上的时间,我们希望每秒做一次.这是使用我们的稳定时钟(这将保证我们不会被系统时钟漂移所欺骗)的一种方法:

function time() {
    const [seconds, nanos] = process.hrtime();
    return seconds * 1000 + nanos / 1000000;
}

async function run() {
    const startTime = time();

    const response = await doRequest();
    await processResponse(response);

    const endTime = time();
    // wait just the right amount of time so we run once second; 
    // if we took more than one second, run again immediately
    const nextRunInMillis = Math.max(0, 1000 - (endTime - startTime));
    setTimeout(run, nextRunInMillis);
}

run();
Run Code Online (Sandbox Code Playgroud)

我做了这个帮助函数time(),它将返回的数组转换为process.hrtime()毫秒分辨率的时间戳; 这个应用程序的分辨率足够

  • @Keith `new Date()` 依赖于系统时钟。由于夏令时边界、NTP 刷新或任何其他原因,该时钟可能会发生变化。Node.JS 提供了一个基于 CPU 滴答(而不是系统时钟)的高分辨率计时器,它不受此类操作的影响。 (2认同)