在Node.js中单调增加时间

这个问题已经在Javascript中得到了回答,但是window.performance.now()在Node.js中显然不可用。

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

原来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(); 

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

Interesting Posts