Javascript 如何测量函数执行所用的时间

Javascript 如何测量函数执行所用的时间,javascript,profiling,Javascript,Profiling,我需要以毫秒为单位获取执行时间 我最初是在2008年问这个问题的。当时被接受的答案是使用,然而,我们现在都同意使用标准API更合适。因此,我将接受的答案改为这一个 使用Firebug,同时启用控制台和Javascript。单击配置文件。重新加载再次单击“配置文件”。查看报告。使用 方法返回自1970年1月1日午夜以来的毫秒数 前 var start=new Date().getTime(); 对于(i=0;i

我需要以毫秒为单位获取执行时间

我最初是在2008年问这个问题的。当时被接受的答案是使用,然而,我们现在都同意使用标准API更合适。因此,我将接受的答案改为这一个


使用Firebug,同时启用控制台和Javascript。单击配置文件。重新加载再次单击“配置文件”。查看报告。

使用

方法返回自1970年1月1日午夜以来的毫秒数

var start=new Date().getTime();
对于(i=0;i<50000;+i){
//做点什么
}
var end=new Date().getTime();
var时间=结束-开始;
警报(“执行时间:”+时间);
使用: 注意:
传递给
time()
timeEnd()
方法的字符串必须匹配
(计时器才能按预期完成)

console.time()
文档:
不要使用Date()。阅读下面的内容。 使用

<script>
var a = performance.now();
alert('do something...');
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>

var a=performance.now();
警惕(‘做某事’);
var b=性能。现在();
警惕(‘需要’+(b-a)+‘ms’);
它的作用是:

  • IE 10++

  • 火狐15++

  • 铬24++

  • 狩猎8++

  • 歌剧15+

  • 安卓4.4++

控制台。时间对您来说可能是可行的,但它是非标准的:

此功能是非标准的,不在标准轨道上。不要在面向Web的生产站点上使用它:它不会适用于所有用户。实现之间也可能存在很大的不兼容性,并且行为可能会在将来发生变化

除了浏览器支持,
performance.now
似乎有可能提供更精确的计时,因为它似乎是
console.time
的基本版本


另外,永远不要对任何东西使用
日期
,因为它会受到“系统时间”更改的影响。这意味着当用户没有准确的系统时间时,我们将得到无效的结果,如“负计时”:

2014年10月,我的系统时钟失控,你猜怎么着。。。。我打开Gmail,看到了我一天中所有的电子邮件“0分钟前发送的”。我还以为Gmail应该是由谷歌的世界级工程师建造的

(将你的系统时钟设置为一年前,然后转到Gmail,这样我们大家都可以开怀大笑。也许有一天我们会有一个关于JS
的日期

谷歌电子表格的功能也受到这个问题的影响


您将使用的唯一时间是希望向用户显示其系统时钟时间。当您想要获取或测量任何东西时,就不需要了。

要进一步扩展vsync的代码,以便能够在NodeJS中将timeEnd作为值返回,请使用这段代码

console.timeEndValue = function(label) { // Add console.timeEndValue, to add a return value
   var time = this._times[label];
   if (!time) {
     throw new Error('No such label: ' + label);
   }
   var duration = Date.now() - time;
   return duration;
};
现在使用如下代码:

console.time('someFunction timer');

someFunction();

var executionTime = console.timeEndValue('someFunction timer');
console.log("The execution time is " + executionTime);

这为您提供了更多的可能性。您可以存储执行时间以用于更多目的,例如在等式中使用它,或存储在数据库中,通过WebSocket发送到远程客户端,在网页上提供服务,等等

var StopWatch = function (performance) {
    this.startTime = 0;
    this.stopTime = 0;
    this.running = false;
    this.performance = performance === false ? false : !!window.performance;
};

StopWatch.prototype.currentTime = function () {
    return this.performance ? window.performance.now() : new Date().getTime();
};

StopWatch.prototype.start = function () {
    this.startTime = this.currentTime();
    this.running = true;
};

StopWatch.prototype.stop = function () {
    this.stopTime = this.currentTime();
    this.running = false;
};

StopWatch.prototype.getElapsedMilliseconds = function () {
    if (this.running) {
        this.stopTime = this.currentTime();
    }

    return this.stopTime - this.startTime;
};

StopWatch.prototype.getElapsedSeconds = function () {
    return this.getElapsedMilliseconds() / 1000;
};

StopWatch.prototype.printElapsed = function (name) {
    var currentName = name || 'Elapsed:';

    console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};
基准

var stopwatch = new StopWatch();
stopwatch.start();

for (var index = 0; index < 100; index++) {
    stopwatch.printElapsed('Instance[' + index + ']');
}

stopwatch.stop();

stopwatch.printElapsed();

是可选的-只需将false传递到StopWatch构造函数中。

如果需要在本地开发计算机上获取函数执行时间,可以使用浏览器的分析工具,也可以使用和等控制台命令

所有现代浏览器都内置了JavaScript分析器。这些分析器应该提供最准确的度量,因为您不必修改现有代码,这可能会影响函数的执行时间

要分析JavaScript,请执行以下操作:

  • 在Chrome中,按F12并选择Profiles选项卡,然后收集JavaScript CPU配置文件
  • 在Firefox中,安装/打开Firebug,然后单击Profile按钮
  • IE 9+中,按F12,单击脚本或探查器(取决于您的IE版本)
或者,在开发机器上,您可以使用和向代码中添加指令插入。Firefox11+、Chrome2+和IE11+中支持的这些函数报告通过
console.time()
启动/停止的计时器
time()
将用户定义的计时器名称作为参数,然后
timeEnd()
报告计时器启动后的执行时间:

function a() {
  console.time("mytimer");
  ... do stuff ...
  var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
}
请注意,只有Firefox在
timeEnd()
调用中返回经过的时间。其他浏览器只是将结果报告给开发人员控制台:
timeEnd()
的返回值未定义

如果您想在野外获得函数执行时间,则必须插入代码。你有几个选择。通过查询
new Date().getTime()
,您可以简单地保存开始和结束时间:

但是,
Date
对象只有毫秒分辨率,并且会受到任何操作系统系统时钟变化的影响。在现代浏览器中,有一个更好的选择

更好的选择是使用,aka
window.performance.now()
now()
在两个重要方面优于传统的
Date.getTime()

  • now()
    是一个分辨率为亚毫秒的双精度字符,表示自页面导航开始以来的毫秒数。它以小数形式返回微秒数(例如,1000.123的值为1秒和123微秒)

  • now()
    是单调递增的。这一点很重要,因为
    Date.getTime()
    可能在后续调用中向前跳,甚至向后跳。值得注意的是,如果操作系统的系统时间被更新(例如原子钟同步),
    Date.getTime()
    也会被更新<代码>现在(
    var StopWatch = function (performance) {
        this.startTime = 0;
        this.stopTime = 0;
        this.running = false;
        this.performance = performance === false ? false : !!window.performance;
    };
    
    StopWatch.prototype.currentTime = function () {
        return this.performance ? window.performance.now() : new Date().getTime();
    };
    
    StopWatch.prototype.start = function () {
        this.startTime = this.currentTime();
        this.running = true;
    };
    
    StopWatch.prototype.stop = function () {
        this.stopTime = this.currentTime();
        this.running = false;
    };
    
    StopWatch.prototype.getElapsedMilliseconds = function () {
        if (this.running) {
            this.stopTime = this.currentTime();
        }
    
        return this.stopTime - this.startTime;
    };
    
    StopWatch.prototype.getElapsedSeconds = function () {
        return this.getElapsedMilliseconds() / 1000;
    };
    
    StopWatch.prototype.printElapsed = function (name) {
        var currentName = name || 'Elapsed:';
    
        console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
    };
    
    var stopwatch = new StopWatch();
    stopwatch.start();
    
    for (var index = 0; index < 100; index++) {
        stopwatch.printElapsed('Instance[' + index + ']');
    }
    
    stopwatch.stop();
    
    stopwatch.printElapsed();
    
    Instance[0] [0ms] [0s]
    Instance[1] [2.999999967869371ms] [0.002999999967869371s]
    Instance[2] [2.999999967869371ms] [0.002999999967869371s]
    /* ... */
    Instance[99] [10.999999998603016ms] [0.010999999998603016s]
    Elapsed: [10.999999998603016ms] [0.010999999998603016s]
    
    function a() {
      console.time("mytimer");
      ... do stuff ...
      var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
    }
    
    function a() {
      var start = new Date().getTime();
      ... do stuff ...
      var end = new Date().getTime();
      var dur = end - start;
    }
    
    function a() {
      var start = window.performance.now();
       ... do stuff ...
      var end = window.performance.now();
      var dur = end - start;
    }
    
    function a() {
      window.performance.mark("start");
      ... do stuff ...
      window.performance.measure("myfunctionduration", "start");
    }
    
    // duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];
    
    //=-=|Source|=-=//
    /**
     * JavaScript Timer Object
     *
     *      var now=timer['elapsed'](); 
     *      timer['stop']();
     *      timer['start']();
     *      timer['reset']();
     * 
     * @expose
     * @method timer
     * @return {number}
     */
    timer=function(){
        var a=Date.now();
        b=0;
        return{
            /** @expose */
            elapsed:function(){return b=Date.now()-a},
            start:function(){return a=Date.now()},
            stop:function(){return Date.now()},
            reset:function(){return a=0}
        }
    }();
    
    //=-=|Google Advanced Optimized|=-=//
    timer=function(){var a=Date.now();b=0;return{a:function(){return b=Date.now()-a},start:function(){return a=Date.now()},stop:function(){return Date.now()},reset:function(){return a=0}}}();
    
    Performance: {
        Timer: {},
        Start: function (name) {
            if (console && console.time) {
                console.time(name);
            } else if (window.performance.now) {
                this.Timer[name] = window.performance.now();
            } else {
                this.Timer[name] = new Date().getTime();
            }
        },
        End: function (name) {
            if (console && console.time) {
                console.timeEnd(name);
            } else {
                var result;
                if (window.performance.now) {
                    result = window.performance.now() - this.Timer[name];
                } else {
                    result = new Date().getTime() - this.Timer[name];
                }
                console.log(name + ": " + result);
            }
        }
    }
    
    var start = new Date().getTime();
    
    for (i = 0; i < 50000; ++i) {
    // JavaScript is not waiting until the for is finished !!
    }
    
    var end = new Date().getTime();
    var time = end - start;
    alert('Execution time: ' + time); 
    
    var start = new Date().getTime();
    
    for (i = 0; i < 50000; ++i) {
      $.ajax({
        url: 'www.oneOfYourWebsites.com',
        success: function(){
           console.log("success");
        }
      });
    }
    
    var end = new Date().getTime();
    var time = end - start;
    alert('Execution time: ' + time); 
    
    var performance = window.performance;
    var t0 = performance.now();
    doWork();
    var t1 = performance.now();
    console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")
    
    var hrTime = process.hrtime()
    console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)
    
    var t0 = process.hrtime();
    //Start of code to measure
    
    //End of code
    var timeInMilliseconds = process.hrtime(t0)[1]/1000000; // dividing by 1000000 gives milliseconds from nanoseconds
    
    var t0 = process.hrtime();
    someAsyncFunction(function(err, results) {
    var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
    
    });
    
    function timer(lap){ 
        if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`); 
        timer.prev = performance.now();
    }
    
    console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');
    
    // Usage: 
    timer()              // set the start
    // do something 
    timer('built')       // logs 'built in: 591.815ms'
    // do something
    timer('copied')      // logs 'copied in: 0.065ms'
    // do something
    timer('compared')    // logs 'compared in: 36.41ms'
    
    function functionTimer() {
        performance.mark('start')
        functionToBeTimed()
        performance.mark('end')
        performance.measure('Start to End', 'start', 'end')
        const measure = performance.getEntriesByName('Start to End')[0]
        console.log(measure.duration)
    }
    
     var start = +new Date();
     callYourFunctionHere();
     var end = +new Date();
     var time = end - start;
     console.log('total execution time = '+ time + 'ms');
    
    export default class Singleton {
    
      static myInstance: Singleton = null;
    
      _timers: any = {};
    
      /**
       * @returns {Singleton}
       */
      static getInstance() {
        if (Singleton.myInstance == null) {
          Singleton.myInstance = new Singleton();
        }
    
        return this.myInstance;
      }
    
      initTime(label: string) {
        this._timers[label] = Date.now();
        return this._timers[label];
      }
    
      endTime(label: string) {
        const endTime = Date.now();
        if (this._timers[label]) {
          const delta = endTime - this._timers[label];
          const finalTime = `${label}: ${delta}ms`;
          delete this._timers[label];
          return finalTime;
        } else {
          return null;
        }
      }
    }
    
    let timed = (f) => (...args)=>{
        let start = performance.now();
        let ret = f(...args);
        console.log(`function ${f.name} took ${(performance.now()-start).toFixed(3)}ms`)
        return ret;   
    }
    
    let test = ()=>{/*does something*/}
    test = timed(test)   // turns the function into a timed function in one line
    test()               // run your code as normal, logs 'function test took 1001.900ms' 
    
    function timer() {
        return (target, propertyKey, descriptor) => {
            const start = Date.now();
            let oldFunc = descriptor.value;
    
            descriptor.value = async function (){
                var result = await oldFunc.apply(this, arguments);
                console.log(Date.now() - start);
                return result;
            }
        }
    }
    
    // Util function 
    function delay(timeout) {
        return new Promise((resolve) => setTimeout(() => {
            resolve();
        }, timeout));
    }
    
    class Test {
        @timer()
        async test(timout) {
            await delay(timout)
            console.log("delay 1");
            await delay(timout)
            console.log("delay 2");
        }
    }
    
    const t = new Test();
    t.test(1000)
    t.test(100)
    
     {
        "plugins": [
            "transform-decorators-legacy"
        ]
     }
    
    const perf = typeof performance !== "undefined" ? performance : require('perf_hooks').performance;
    const DIGITS = 2;
    
    let _timers = {};
    
    const _log = (label, delta?) => {
        if (_timers[label]) {
            console.log(`${label}: ` + (delta ? `${delta.toFixed(DIGITS)} ms last, ` : '') +
                `${_timers[label].total.toFixed(DIGITS)} ms total, ${_timers[label].cycles} cycles`);
        }
    };
    
    export const Stopwatch = {
        start(label) {
            const now = perf.now();
            if (_timers[label]) {
                if (!_timers[label].started) {
                    _timers[label].started = now;
                }
            } else {
                _timers[label] = {
                    started: now,
                    total: 0,
                    cycles: 0
                };
            }
        },
        /** Returns total elapsed milliseconds, or null if stopwatch doesn't exist. */
        stop(label, log = false) {
            const now = perf.now();
            if (_timers[label]) {
                let delta;
                if(_timers[label].started) {
                    delta = now - _timers[label].started;
                    _timers[label].started = null;
                    _timers[label].total += delta;
                    _timers[label].cycles++;
                }
                log && _log(label, delta);
                return _timers[label].total;
            } else {
                return null;
            }
        },
        /** Logs total time */
        log: _log,
        delete(label) {
            delete _timers[label];
        }
    };
    
    var timer = -performance.now();
    
    // Do something
    
    timer += performance.now();
    console.log("Time: " + (timer/1000).toFixed(5) + " sec.")
    
    console.time('function');
    //run the function in between these two lines for that you need to 
    //measure time taken by the function. ("ex. function();")
    console.timeEnd('function');
    
    var v1 = performance.now();
    //run the function here for which you have top measure the time 
    var v2 = performance.now();
    console.log("total time  taken = "+(v2-v1)+"milliseconds");
    
    var h2 = +new Date(); //or
    var h2 = new Date().getTime();
    for(i=0;i<500;i++) { /* do something */}
    var h3 = +new Date();   //or 
    var h3 = new Date().getTime();
    var timeTaken = h3-h2;
    console.log("time ====", timeTaken);
    
    const { performance, PerformanceObserver } = require('perf_hooks');
    
    const measures = []
    
    const obs = new PerformanceObserver(list => measures.push(...list.getEntries()));
    obs.observe({ entryTypes: ['measure'] });
    const getEntriesByType = cb => cb(measures);
    
    const doSomething = val => {
      performance.mark('beginning of the process');
    
      val *= 2;
    
      performance.mark('after multiplication');
    
      performance.measure('time taken', 'beginning of the process', 'after multiplication');
    
      getEntriesByType(entries => {
        entries.forEach(entry => console.log(entry));
      })
    
      return val;
    }
    
    doSomething(4);
    
    var time0 = performance.now(); // Store the time at this point into time0
    
    yourFunction();   // The function you're measuring time for 
    
    var time1 = performance.now(); // Store the time at this point into time1
    
    console.log("youFunction took " + (time1 - time0) + " milliseconds to execute");
    
    console.time('someFunction');
    
    someFunction(); // Whatever is timed goes between the two "console.time"
    
    console.timeEnd('someFunction');