window.performance.now() equivalent in nodejs?

こ雲淡風輕ζ 提交于 2019-11-30 04:10:37
barry-johnson

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.

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

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"

What about?

console.time('FooTimer');
// do the work
console.timeEnd('FooTimer');
Erik Barke

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

To sum up and avoiding using perf_hooks

const performance = {
        now: function(start) {
            if ( !start ) return process.hrtime();
            var end = process.hrtime(start);
            return Math.round((end[0]*1000) + (end[1]/1000000));
        }
    }
console.log('performance', performance.now());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!