【问题标题】:Write console.time result to variable将 console.time 结果写入变量
【发布时间】:2015-07-16 19:10:49
【问题描述】:

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

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

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    不,但您可以改用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/

    【讨论】:

      【解决方案2】:

      我知道这个问题有点老了,但现在你可以在 Node.js 中使用performance 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 中添加的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-09
        • 2021-04-01
        • 2019-07-06
        • 1970-01-01
        • 2017-06-11
        • 1970-01-01
        • 1970-01-01
        • 2013-04-29
        相关资源
        最近更新 更多