114

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.

shriek
  • 5,605
  • 8
  • 46
  • 75

9 Answers9

159

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());
Gajus
  • 69,002
  • 70
  • 275
  • 438
  • 3
    or ```import { performance } from "perf_hooks";``` for modules (.mjs) – Ali Mert Çakar May 02 '22 at 23:31
  • Or even better, "for modules" without the .mjs extension as that was Node.js's initial solution to the fact that they had huge problems swapping between cjs and esm formats. JS never dictated that change, and ESM code can use .js just fine, with modern Node supporting that as long as you remember to make your codebase as using modern module syntax. – Mike 'Pomax' Kamermans Aug 08 '23 at 21:10
62

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.

Note: Since the version 8.5.0 of Node, you can use performance.now()

Slim
  • 5,527
  • 13
  • 45
  • 81
barry-johnson
  • 3,204
  • 1
  • 17
  • 19
31

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"

jaggedsoft
  • 3,858
  • 2
  • 33
  • 41
17

What about?

console.time('FooTimer');
// do the work
console.timeEnd('FooTimer');
tenbits
  • 7,568
  • 5
  • 34
  • 53
  • 1
    Beware console.time() if you're using promises, await, etc. the time()/timeEnd() pair seem to work using global state - if you time the same tag in parallel, things won't work right. – Shorn Nov 28 '17 at 23:18
  • So this may work, but if you want to pragmatically hold onto that time instead this ( process.hrtime() ) is your only other 'in process' way. You could create a parent process and watch stdout, but that's a last resort. EDIT: Or it looks like there's the performance timing api in nodejs as of 8.5+ - https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_timing_api – Eric Hodonsky Apr 12 '18 at 22:31
4

process.uptime()


"The process.uptime() method returns the number of seconds the current Node.js process has been running.

The return value includes fractions of a second. Use Math.floor() to get whole seconds."

Example: Measure For Loop Execution Time


const nemo = ['nemo'];

function findNemo(array) {
  
  let start_time = process.uptime();

  for (let iteration = 0; iteration < array.length; iteration++) {
     if (array[iteration] === 'nemo') {
        console.log("Found Nemo");
     }
  }

  let end_time = process.uptime();

  console.log("For loop took this much time: ", end_time - start_time);
}

findNemo(nemo);

Example Output


enter image description here

1

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());
Community
  • 1
  • 1
Erik Barke
  • 444
  • 5
  • 12
1

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());
loretoparisi
  • 15,724
  • 11
  • 102
  • 146
0

This method came into existence in version 8.5.0 of nodejs https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_measurement_apis

apenas
  • 39
  • 2
-2

compare solutions with and without loop.

Note down, which makes a difference performance wise ?

Try it out in JS snippets in developer tools or any JS editor.

function sum(n) {
  let total = 0;
  for (let i = 0; i <= n; i++) {
    total += i;
  }
  return total;
}

var t1 = performance.now();

sum(100000000);

var t2 = performance.now();

console.log(`time elapsed: ${(t2-t1)/1000} seconds.`);

function addupto(n) {
  return n * (n + 1) / 2;
}

var t3 = performance.now();

addupto(100000000);

var t4 = performance.now();

console.log(`time elapsed: ${(t4-t3)/1000} seconds.`);
cloned
  • 6,346
  • 4
  • 26
  • 38