写控制台.时间结果变量

Write console.time result to variable

本文关键字:变量 结果 时间 控制台      更新时间:2023-09-26

是否可以将console.time()结果写入变量?

console.time('It''s saved!');
fn();
var a = console.timeEnd('It''s saved!');
console.log(a) // => It's saved!: 16ms

不可以,但是您可以使用window.performance.now()代替

var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
http://jsfiddle.net/8Lt250wa/

我知道这个问题有点老了,但现在你可以在Node.js中使用性能Api:

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

或使用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();

注意:性能api是在Node v8.5.0中添加的