13

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?

juan garcia
  • 1,326
  • 2
  • 23
  • 56
  • see also https://stackoverflow.com/questions/313893/how-to-measure-time-taken-by-a-function-to-execute – mb21 Aug 07 '20 at 14:37
  • @mb21 thx, in particular I was needing performance in Nodejs, although I did not know about performance.now for browsers and it is a good reference – juan garcia Aug 09 '20 at 08:15

5 Answers5

17

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`);
Alex Michailidis
  • 4,078
  • 1
  • 16
  • 35
  • 1
    A typescript utility function to get the milliseconds: `const getMsFromHrTime = (diff: ReturnType) => (diff[0] * NS_PER_SEC + diff[1]) * MS_PER_NS;` – Tom Jul 04 '20 at 09:52
  • 1
    For 2020 people coming across this: use process.hrtime.bigint(). The non bigint version has been made legacy. – Hunter Kohler Jul 12 '21 at 19:22
11

Starting from Node v8.5, you can use browser-equivalent performance.now() which is easier to use than process.hrtime because it outputs the time in milliseconds directly, therefore you don't have to do a conversion as in process.hrtime

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

const start = performance.now();
doSomething();
const end = performance.now();

console.log(`time taken: ${end - start}ms`);

You can find more info from Node.js Docs on Performance API.

Deepal
  • 1,729
  • 5
  • 24
  • 34
5

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`;
    }
}
Matt
  • 5,800
  • 1
  • 44
  • 40
3
var startTime = new Date();
for(let i; i < 10000; i++) {
// Just to simulate the process
}
var endTime = new Date() - startTime;

You will get the total time that it takes to complete the operation

Mr.Throg
  • 925
  • 6
  • 21
  • May be using momentjs to substract time could be an option const startTime = moment(Date.now()); //process const totalTime = moment(Date.now()).substract(startTime); – juan garcia Feb 13 '18 at 14:16
0

See here https://alligator.io/js/console-time-timeend/

var begin=console.time('t');

for(let i; i < 100000; i++) {
// Just to simulate the process
}
var end= console.timeEnd('t');

var timeSpent=(end-begin) / 1000 + "secs";
аlex
  • 5,426
  • 1
  • 29
  • 38