Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure process time with Node Js?

I would like to do the following:

console.time("processA");
for(let i; i < 10000; i++) {
// Just to simulate the process
}
console.timeEnd("processA");

but I want to capture the time end and use my own logger of information with it.

Is it possible to handle the console output of the timeEnd?

How can I measure the time interval of a process in nodejs?

like image 981
juan garcia Avatar asked Feb 13 '18 14:02

juan garcia


2 Answers

Since I'm using timers in multiple places, I wrote a simple class based on Alex's answer:

const t = new Timer('For Loop')
// your code
t.runtimeMs()     // => 1212.34
t.runtimeMsStr()  // => 'For Loop took 1232.34 milliseconds'

Here's the code:

class Timer {
    // Automatically starts the timer
    constructor(name = 'Benchmark') {
        this.NS_PER_SEC = 1e9;
        this.MS_PER_NS = 1e-6
        this.name = name;
        this.startTime = process.hrtime();
    }

    // returns the time in ms since instantiation
    // can be called multiple times
    runtimeMs() {
        const diff = process.hrtime(this.startTime);
        return (diff[0] * this.NS_PER_SEC + diff[1]) * this.MS_PER_NS;
    }

    // retuns a string: the time in ms since instantiation
    runtimeMsStr() {
        return `${this.name} took ${this.runtimeMs()} milliseconds`;
    }
}
like image 188
Matt Avatar answered Oct 19 '22 01:10

Matt


Since you are targeting nodejs, you can use process.hrtime as stated in the docs

The process.hrtime() method returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array, where nanoseconds is the remaining part of the real time that can't be represented in second precision.

So you can measure timings up to nanosecond, something that console.time can't, as you can see in your example console.time or Date difference measures 0s.

For example:

const NS_PER_SEC = 1e9;
const MS_PER_NS = 1e-6
const time = process.hrtime();
for (let i; i < 10000; i++) {
  // Just to simulate the process
}
const diff = process.hrtime(time);
console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
console.log(`Benchmark took ${ (diff[0] * NS_PER_SEC + diff[1])  * MS_PER_NS } milliseconds`);
like image 16
Alex Michailidis Avatar answered Oct 19 '22 02:10

Alex Michailidis