Javascript 如何在 Node.js 中获取微时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11725691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:51:56  来源:igfitidea点击:

How to get a microtime in Node.js?

javascriptnode.jsv8

提问by NiLL

How can I get the most accurate time stamp in Node.js?

如何在 Node.js 中获得最准确的时间戳?

ps My version of Node.js is 0.8.X and the node-microtime extensiondoesn't work for me (crash on install)

ps 我的 Node.js 版本是 0.8.X 并且node-microtime 扩展对我不起作用(安装时崩溃)

回答by Myrne Stol

In Node.js, "high resolution time" is made available via process.hrtime. It returns a array with first element the time in seconds, and second element the remaining nanoseconds.

在 Node.js 中,“高分辨率时间”通过process.hrtime. 它返回一个数组,其中第一个元素是时间(以秒为单位),第二个元素是剩余的纳秒。

To get current time in microseconds, do the following:

要以微秒为单位获取当前时间,请执行以下操作:

var hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)

(Thanks to itaifrenkelfor pointing out an error in the conversion above.)

(感谢itaifrenkel指出上述转换中的错误。)

In modern browsers, time with microsecond precision is available as performance.now. See https://developer.mozilla.org/en-US/docs/Web/API/Performance/nowfor documentation.

在现代浏览器中,具有微秒精度的时间可作为performance.now. 有关文档,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Performance/now

I've made an implementation of this function for Node.js, based on process.hrtime, which is relatively difficult to use if your solely want to compute time differential between two points in a program. See http://npmjs.org/package/performance-now. Per the spec, this function reports time in milliseconds, but it's a float with sub-millisecond precision.

我已经为 Node.js 实现了这个函数,基于process.hrtime,如果您只想计算程序中两点之间的时间差,则相对难以使用。请参阅http://npmjs.org/package/performance-now。根据规范,此函数以毫秒为单位报告时间,但它是一个具有亚毫秒精度的浮点数。

In Version 2.0 of this module, the reported milliseconds are relative to when the node process was started (Date.now() - (process.uptime() * 1000)). You need to add that to the result if you want a timestamp similar to Date.now(). Also note that you should bever recompute Date.now() - (process.uptime() * 1000). Both Date.nowand process.uptimeare highly unreliable for precise measurements.

在此模块的 2.0 版中,报告的毫秒数与节点进程启动时间 ( Date.now() - (process.uptime() * 1000)) 相关。如果您想要类似于 的时间戳,则需要将其添加到结果中Date.now()。另请注意,您应该永远重新计算Date.now() - (process.uptime() * 1000)Date.now和两者process.uptime对于精确测量都非常不可靠。

To get current time in microseconds, you can use something like this.

要以微秒为单位获取当前时间,您可以使用这样的方法。

var loadTimeInMS = Date.now()
var performanceNow = require("performance-now")
console.log((loadTimeInMS + performanceNow()) * 1000)

See also: Does JavaScript provide a high resolution timer?

另请参阅:JavaScript 是否提供高分辨率计时器?

回答by Niet the Dark Absol

new Date().getTime()? This gives you a timestamp in milliseconds, which is the most accurate that JS will give you.

new Date().getTime()? 这会给你一个以毫秒为单位的时间戳,这是 JS 会给你的最准确的。

Update: As stated by vaughan, process.hrtime()is available within Node.js - its resolution are nanoseconds and therefore its much higher, also this doesn't mean it has to be more exact.

更新:正如 vaughan 所说,process.hrtime()在 Node.js 中可用 - 它的分辨率是纳秒,因此它要高得多,但这并不意味着它必须更精确。

PS.: Just to be clearer, process.hrtime()returns you a tuple Arraycontaining the current high-resolution real time in a [seconds, nanoseconds]

PS.:为了更清楚,在[秒,纳秒]中process.hrtime()返回一个Array包含当前高分辨率实时的元组

回答by Abdennour TOUMI

now('milli'); //  120335360.999686
now('micro') ; // 120335360966.583
now('nano') ; //  120335360904333

Known that nowis :

已知的now是:

const now = (unit) => {

  const hrTime = process.hrtime();

  switch (unit) {

    case 'milli':
      return hrTime[0] * 1000 + hrTime[1] / 1000000;

    case 'micro':
      return hrTime[0] * 1000000 + hrTime[1] / 1000;

    case 'nano':
      return hrTime[0] * 1000000000 + hrTime[1];

    default:
      return now('nano');
  }

};

回答by d4nyll

The BigIntdata type is supported since Node.js 10.7.0. (see also the blog post announcement). For these supported versions of Node.js, the process.hrtime([time])method is now regarded as 'legacy', replaced by the process.hrtime.bigint()method.

BigInt自Node.js的10.7.0数据类型的支持。(另请参阅博客文章公告)。对于这些受支持的 Node.js 版本,该process.hrtime([time])方法现在被视为“遗留”,由process.hrtime.bigint()方法取代。

The bigintversion of the process.hrtime()method returning the current high-resolution real time in a bigint.

bigint该版本process.hrtime()返回在当前高分辨率实时方法bigint

const start = process.hrtime.bigint();
// 191051479007711n

setTimeout(() => {
  const end = process.hrtime.bigint();
  // 191052633396993n

  console.log(`Benchmark took ${end - start} nanoseconds`);
  // Benchmark took 1154389282 nanoseconds
}, 1000);


tl;dr

tl;博士

  • Node.js 10.7.0+ - Use process.hrtime.bigint()
  • Otherwise - Use process.hrtime()
  • Node.js 10.7.0+ - 使用 process.hrtime.bigint()
  • 否则 - 使用 process.hrtime()

回答by mikemaccana

There's also https://github.com/wadey/node-microtime:

还有https://github.com/wadey/node-microtime

> var microtime = require('microtime')
> microtime.now()
1297448895297028

回答by krb686

Node.js nanotimer

Node.js 纳米计时器

I wrote a wrapper library/object for node.js on top of the process.hrtimefunction call. It has useful functions, like timing synchronous and asynchronous tasks, specified in seconds, milliseconds, micro, or even nano, and follows the syntax of the built in javascript timer so as to be familiar.

我在process.hrtime函数调用之上为 node.js 编写了一个包装库/对象。它具有有用的功能,例如定时同步和异步任务,以秒,毫秒,微甚至纳米指定,并遵循内置javascript计时器的语法,以便于熟悉。

Timer objects are also discrete, so you can have as many as you'd like, each with their own setTimeoutor setIntervalprocess running.

计时器对象也是离散的,因此您可以拥有任意数量的对象,每个对象都有自己的setTimeoutsetInterval正在运行的进程。

It's called nanotimer. Check it out!

它被称为纳米计时器。一探究竟!

回答by Ross

To work with more precision than Date.now(), but with milliseconds in float precision:

要以比 更高的精度工作Date.now(),但浮点精度为毫秒:

function getTimeMSFloat() {
    var hrtime = process.hrtime();
    return ( hrtime[0] * 1000000 + hrtime[1] / 1000 ) / 1000;
}

回答by Cameron Tacklind

Get hrtimeas single number in one line:

hrtime在一行中获取单个数字:

const begin = process.hrtime();
// ... Do the thing you want to measure
const nanoSeconds = process.hrtime(begin).reduce((sec, nano) => sec * 1e9 + nano)

Array.reduce, when given a single argument, will use the array's first element as the initial accumulatorvalue. One could use 0as the initial value and this would work as well, but why do the extra * 0.

Array.reduce,当给定一个参数时,将使用数组的第一个元素作为初始accumulator值。可以将其0用作初始值,这也可以使用,但是为什么要使用额外的* 0.

回答by pirs

I'm not so proud about this solution but you can have timestamp in microsecond or nanosecondin this way:

我对这个解决方案并不感到自豪,但您可以通过这种方式获得微秒或纳秒的时间戳

const microsecond = () => Number(Date.now() + String(process.hrtime()[1]).slice(3,6))
const nanosecond = () => Number(Date.now() + String(process.hrtime()[1]).slice(3))

// usage
microsecond() // return 1586878008997591
nanosecond()  // return 1586878009000645600

// Benchmark with 100 000 iterations
// Date.now: 7.758ms
// microsecond: 33.382ms
// nanosecond: 31.252ms

Know that:

我知道:

  • This solution works exclusively with node.js,
  • This is about 3 to 10 times slowerthan Date.now()
  • Weirdly, it seems very accurate, hrTime seems to follow exactly js timestamp ticks.
  • You can replace Date.now()by Number(new Date())to get timestamp in milliseconds
  • 此解决方案仅适用于 node.js
  • 这是一个关于3至10倍慢Date.now()
  • 奇怪的是,它似乎非常准确,hrTime 似乎完全遵循 js 时间戳记。
  • 您可以替换Date.now()Number(new Date())以毫秒为单位获取时间戳

Edit:

编辑:

Here a solution to have microsecond with comma, however, the number version will be rounded natively by javascript. So if you want the same format every time, you should use the String version of it.

这里有一个带有逗号的微秒的解决方案,但是,数字版本将由 javascript 本机四舍五入。所以如果你每次都想要相同的格式,你应该使用它的 String 版本。

const microsecondWithCommaString = () => (Date.now() + '.' + String(process.hrtime()[1]).slice(3,7))
const microsecondWithComma = () => Number(Date.now() + '.' + String(process.hrtime()[1]).slice(3,7))

microsecondWithCommaString() // return "1586883629984.8997"
microsecondWithComma() // return 1586883629985.966

回答by Saravana Kumar Chinnaraj

process.hrtime() not give current ts.

process.hrtime() 没有给出当前的 ts。

This should work.

这应该有效。

 const loadNs       = process.hrtime(),
        loadMs       = new Date().getTime(),
        diffNs       = process.hrtime(loadNs),
        microSeconds = (loadMs * 1e6) + (diffNs[0] * 1e9) + diffNs[1]

  console.log(microSeconds / 1e3)