window.performance.now() equivalent in nodejs?

2019-02-03 21:58发布

I think the question is straight forward.

I'm looking for something that's similar to window.performance.now() in nodejs V8 engine.

Right now I'm just using:-

var now = Date.now();
//do some processing..
console.log("time elapsed:", Date.now() - now);

But, I read that window.performance.now() is lot more accurate than using the date because of the what's defined here.

5条回答
趁早两清
2楼-- · 2019-02-03 22:23

Node v8.5.0 has added Performance Timing API, which includes the performance#now(), e.g.

const {
  performance
} = require('perf_hooks');

console.log('performance', performance.now());
查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-03 22:26

What about?

console.time('FooTimer');
// do the work
console.timeEnd('FooTimer');
查看更多
霸刀☆藐视天下
4楼-- · 2019-02-03 22:29

Here's a shortcut for process.hrtime() that returns milliseconds instead of microseconds:

function clock(start) {
    if ( !start ) return process.hrtime();
    var end = process.hrtime(start);
    return Math.round((end[0]*1000) + (end[1]/1000000));
}

Usage:

var start = clock();
// do some processing that takes time
var duration = clock(start);
console.log("Took "+duration+"ms");

Will output something like "Took 200ms"

查看更多
beautiful°
5楼-- · 2019-02-03 22:31

I would only mention that three of the reasons the author gives for the preference of the timing API in the browser wouldn't seem to apply directly to a node situation, and the fourth, the inaccuracy of Javscript time, cites an article from 2008, and I would strongly caution against relying on older material regarding Javascript performance specifics, particularly given the recent round of performance improvements all the engines have made to support "HTML5" apps.

However, in answer to your question, you should look at process.hrtime()

UPDATE: The present package (available via npm install present) provides some sugar around hrtime if you'd like it.

查看更多
劫难
6楼-- · 2019-02-03 22:34

Here's a Typescript version with process.hrtime(), based on NextLocal's answer:

class Benchmark {

    private start = process.hrtime();

    public elapsed(): number {
        const end = process.hrtime(this.start);
        return Math.round((end[0] * 1000) + (end[1] / 1000000));
    }
}

export = Benchmark;

Usage:

import Benchmark = require("./benchmark");

const benchmark = new Benchmark();

console.log(benchmark.elapsed());
查看更多
登录 后发表回答