Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write console.time result to variable

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
like image 391
Bob Napkin Avatar asked Jul 16 '15 19:07

Bob Napkin


2 Answers

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/

like image 192
Andreas Avatar answered Sep 18 '22 00:09

Andreas


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.

like image 25
Slim Avatar answered Sep 21 '22 00:09

Slim