将console.time结果写入变量

Bob*_*kin 3 javascript node.js

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

console.time('It\'s saved!');
fn();
var a = console.timeEnd('It\'s saved!');
console.log(a) // => It's saved!: 16ms
Run Code Online (Sandbox Code Playgroud)

Sli*_*lim 11

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

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

或使用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();
Run Code Online (Sandbox Code Playgroud)

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


And*_*eas 8

否,但您可以window.performance.now()改用

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

http://jsfiddle.net/8Lt250wa/