13

Is it possible to write console.time() result to variable?

console.time('It\'s saved!');
fn();
var a = console.timeEnd('It\'s saved!');
console.log(a) // => It's saved!: 16ms
Bob Napkin
  • 566
  • 6
  • 15

2 Answers2

23

No, but you can use window.performance.now() instead

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

http://jsfiddle.net/8Lt250wa/

Andreas
  • 21,535
  • 7
  • 47
  • 56
11

I know that the question is a bit old but now you can use performance Api in Node.js:

const {performance} = require('perf_hooks');
const start = performance.now();
fn();
const end = performance.now();
console.log(`${end - start}ms`);

or use timerify():

const {
  performance,
  PerformanceObserver
} = require('perf_hooks');

function fn() {
 // some stuff here
}

const wrapped = performance.timerify(fn);

const obs = new PerformanceObserver((list) => {
  console.log(list.getEntries()[0].duration);
  obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });

// A performance timeline entry will be created
wrapped();

Note: the performance api was added in Node v8.5.0.

Slim
  • 5,527
  • 13
  • 45
  • 81