ReferenceError: performance is not defined when using performance.now()

Elsban picture Elsban · Sep 27, 2017 · Viewed 13.3k times · Source

I am getting an error ReferenceError: performance is not defined when trying to use performance.now() to measure the execution time of a function call:

export async function find(someId: string, ctx: context.IContext) {

      try {
        var t0 = performance.now();

        var res = someModel.find(someId, ctx.cookies);

        var t1 = performance.now();
        console.log("Call to find took " + (t1 - t0) + " milliseconds.");

        return res;
      } catch (err) {
        console.error(err);
        throw err;
      }
    }

Any ideas how I can fix this?

Answer

gilmatic picture gilmatic · May 4, 2018

I know this is tagged front-end but if anyone comes across this looking for a node.js solution (like me), you need to first require performance from the perf_hooks module (available in node 8.5+).

const {performance} = require('perf_hooks');
const t0 = performance.now();
...