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.

9 Answers 9

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());
2
  • 3
    or import { performance } from "perf_hooks"; for modules (.mjs) May 2, 2022 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. Aug 8 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()

4
  • Yup, that's just what I need. Thanks. I'll take a look at present too.
    – shriek
    Apr 11, 2014 at 4:49
  • There's also the appropriately named npmjs.com/package/performance-now May 19, 2017 at 13:46
  • Which author? Please include the context in your answer. Jan 15, 2018 at 16:32
  • 2
    The author of the link posted in the original question, obviously. The question is the context. Adding it would be a redundancy, not context. Jan 25, 2018 at 3:47
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"

17

What about?

console.time('FooTimer');
// do the work
console.timeEnd('FooTimer');
2
  • 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, 2017 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+ - nodejs.org/api/… Apr 12, 2018 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());
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());
3
  • 2
    Why would we want to avoid perf_hooks?
    – Spurious
    Jan 8, 2020 at 12:01
  • 3
    Because it was added in Node v8.5.0 so for backwards compatibility, that maybe required in some circumstances... Jan 8, 2020 at 12:04
  • Thanks a lot for the explanation, makes sense!
    – Spurious
    Jan 8, 2020 at 13:18
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

-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.`);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.