How to measure time taken by a function to execute












862















I need to get execution time in milliseconds.




I originally asked this question back in 2008. The accepted answer
then was to use new Date().getTime() However, we can all agree now
that using the standard performance.now() API is more
appropriate. I am therefore changing the accepted answer to this one.











share|improve this question




















  • 3





    Often a statement on what you are trying to accomplish with the execution time can prove to be far more useful than answering the question alone. These days, using Profiling in Firebug or Chrome Dev tools is often a far better way of finding the code that is sucking up your cpu juice.

    – oligofren
    Mar 6 '13 at 10:04













  • here's how you can do it the classic Date way, which gives you ms and is sufficient for the majority of cases I think albertech.blogspot.com/2015/07/… ... but yeah you should really look at Performance.now

    – jar
    Oct 6 '16 at 19:53













  • performance.now() does not work in Node. new Date().getTime() will work in Node.

    – Ryan Walker
    Sep 11 '18 at 22:50
















862















I need to get execution time in milliseconds.




I originally asked this question back in 2008. The accepted answer
then was to use new Date().getTime() However, we can all agree now
that using the standard performance.now() API is more
appropriate. I am therefore changing the accepted answer to this one.











share|improve this question




















  • 3





    Often a statement on what you are trying to accomplish with the execution time can prove to be far more useful than answering the question alone. These days, using Profiling in Firebug or Chrome Dev tools is often a far better way of finding the code that is sucking up your cpu juice.

    – oligofren
    Mar 6 '13 at 10:04













  • here's how you can do it the classic Date way, which gives you ms and is sufficient for the majority of cases I think albertech.blogspot.com/2015/07/… ... but yeah you should really look at Performance.now

    – jar
    Oct 6 '16 at 19:53













  • performance.now() does not work in Node. new Date().getTime() will work in Node.

    – Ryan Walker
    Sep 11 '18 at 22:50














862












862








862


250






I need to get execution time in milliseconds.




I originally asked this question back in 2008. The accepted answer
then was to use new Date().getTime() However, we can all agree now
that using the standard performance.now() API is more
appropriate. I am therefore changing the accepted answer to this one.











share|improve this question
















I need to get execution time in milliseconds.




I originally asked this question back in 2008. The accepted answer
then was to use new Date().getTime() However, we can all agree now
that using the standard performance.now() API is more
appropriate. I am therefore changing the accepted answer to this one.








javascript profiling






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 6 '16 at 20:33







Julius A

















asked Nov 24 '08 at 11:09









Julius AJulius A

13.4k256589




13.4k256589








  • 3





    Often a statement on what you are trying to accomplish with the execution time can prove to be far more useful than answering the question alone. These days, using Profiling in Firebug or Chrome Dev tools is often a far better way of finding the code that is sucking up your cpu juice.

    – oligofren
    Mar 6 '13 at 10:04













  • here's how you can do it the classic Date way, which gives you ms and is sufficient for the majority of cases I think albertech.blogspot.com/2015/07/… ... but yeah you should really look at Performance.now

    – jar
    Oct 6 '16 at 19:53













  • performance.now() does not work in Node. new Date().getTime() will work in Node.

    – Ryan Walker
    Sep 11 '18 at 22:50














  • 3





    Often a statement on what you are trying to accomplish with the execution time can prove to be far more useful than answering the question alone. These days, using Profiling in Firebug or Chrome Dev tools is often a far better way of finding the code that is sucking up your cpu juice.

    – oligofren
    Mar 6 '13 at 10:04













  • here's how you can do it the classic Date way, which gives you ms and is sufficient for the majority of cases I think albertech.blogspot.com/2015/07/… ... but yeah you should really look at Performance.now

    – jar
    Oct 6 '16 at 19:53













  • performance.now() does not work in Node. new Date().getTime() will work in Node.

    – Ryan Walker
    Sep 11 '18 at 22:50








3




3





Often a statement on what you are trying to accomplish with the execution time can prove to be far more useful than answering the question alone. These days, using Profiling in Firebug or Chrome Dev tools is often a far better way of finding the code that is sucking up your cpu juice.

– oligofren
Mar 6 '13 at 10:04







Often a statement on what you are trying to accomplish with the execution time can prove to be far more useful than answering the question alone. These days, using Profiling in Firebug or Chrome Dev tools is often a far better way of finding the code that is sucking up your cpu juice.

– oligofren
Mar 6 '13 at 10:04















here's how you can do it the classic Date way, which gives you ms and is sufficient for the majority of cases I think albertech.blogspot.com/2015/07/… ... but yeah you should really look at Performance.now

– jar
Oct 6 '16 at 19:53







here's how you can do it the classic Date way, which gives you ms and is sufficient for the majority of cases I think albertech.blogspot.com/2015/07/… ... but yeah you should really look at Performance.now

– jar
Oct 6 '16 at 19:53















performance.now() does not work in Node. new Date().getTime() will work in Node.

– Ryan Walker
Sep 11 '18 at 22:50





performance.now() does not work in Node. new Date().getTime() will work in Node.

– Ryan Walker
Sep 11 '18 at 22:50












21 Answers
21






active

oldest

votes


















1296














Using performance.now():



var t0 = performance.now();

doSomething(); // <---- The function you're measuring time for

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



NodeJs: it is required to import the performance class






Using console.time: (non-standard) (living standard)



console.time('someFunction');

someFunction(); // Whatever is timed goes between the two "console.time"

console.timeEnd('someFunction');


Note:
The string being pass to the time() and timeEnd() methods must match
(for the timer to finish as expected).





console.time() documentations:




  1. NodeJS documentation regarding

  2. MDN (client-side) documentation







share|improve this answer





















  • 18





    It's supported by Chrome Developer Tools as well now.

    – julien_c
    Mar 15 '12 at 11:00






  • 3





    This is currently the best way to collect accurate timings from what I understand.

    – Ash Blue
    May 5 '12 at 2:18






  • 4





    Don't you need to execute the function between those two statements? You now measure the time it takes to define it, not to execute it. Correct me if I'm wrong...

    – Cristian
    Sep 4 '12 at 22:06






  • 2





    Link to the MDN article about this feature: developer.mozilla.org/en-US/docs/DOM/console.time

    – nullability
    Feb 19 '13 at 17:19






  • 6





    yes you can do `totalTime += console.timeEnd('timer')' and do it for each timer

    – vsync
    Jun 19 '13 at 15:28



















584














use new Date().getTime()




The getTime() method returns the number of milliseconds since midnight of January 1, 1970.




ex.



var start = new Date().getTime();

for (i = 0; i < 50000; ++i) {
// do something
}

var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);





share|improve this answer





















  • 9





    Note that you can substitute +new Date() for the getTime() call: var start = +new Date(); // do stuff alert("Execution time: "+(+new Date())-start);

    – J c
    Nov 24 '08 at 13:00






  • 47





    Timings are not accurate because Date is not intended for this functionality. I'm going to be bold here and say you should use vsync's example if you want accurate timing. Although it only works in Chrome and Firefox ATM.

    – Ash Blue
    May 5 '12 at 2:17






  • 9





    Beware, the getMilliseconds() gives you the millisecond fraction of the current second. If you replace getTime() with getMilliseconds() you can get negative results if you cross a second.

    – RickyA
    Jan 10 '13 at 15:47






  • 6





    The answer by vsync is far more correct by todays standards, and using Date() can result in very erronous results being displayed, especially on the Windows platform where results may be rounded+floored to the nearest 15ms boundary, resulting in weird stuff such as 0ms timings on tiny code bits.

    – oligofren
    Mar 6 '13 at 9:59






  • 28





    @AshBlue, we should use window.performance.now. See stackoverflow.com/a/15641427/632951

    – Pacerier
    Nov 2 '13 at 2:17





















382














Don't use Date(). Read below.



Use performance.now():



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


It works on:




  • IE 10 ++


  • FireFox 15 ++


  • Chrome 24 ++


  • Safari 8 ++


  • Opera 15 ++


  • Android 4.4 ++


  • etc, etc



console.time may be viable for you, but it's non-standard §:




This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.




Besides browser support, performance.now seems to have the potential to provide more accurate timings as it appears to be the bare-bones version of console.time.





<rant> Also, DON'T EVER use Date for anything because it's affected by changes in "system time". Which means we will get invalid results —like "negative timing"— when the user doesn't have an accurate system time:




On Oct 2014, my system clock went haywire and guess what.... I opened Gmail and saw all of my day's emails "sent 0 minutes ago". And I'd thought Gmail is supposed to be built by world-class engineers from Google.......




(Set your system clock to one year ago and go to Gmail so we can all have a good laugh. Perhaps someday we will have a Hall of Shame for JS Date.)



Google Spreadsheet's now() function also suffers from this problem.



The only time you'll be using Date is when you want to show the user his system clock time. Not when you want to get the time or to measure anything.






share|improve this answer





















  • 3





    Just what I was looking for! I want to be able to add several times together, can't really do that with console times.

    – Ray
    Sep 29 '13 at 13:33






  • 6





    note that this isn't supported in safari yet: developer.mozilla.org/en-US/docs/Web/API/Performance.now()

    – Akos K
    Nov 1 '13 at 21:11






  • 2





    I use Firebug Profile and performance.now(), and they both work well. Performance.now() confirms my result from Profile.

    – Vincent Jia
    Feb 11 '14 at 10:01






  • 2





    Doesn't work in my biggest hangup, which is IE7 (corporate customers.) I don't care about measuring performance in chrome, it's always lightning fast.

    – Nick
    Mar 3 '14 at 18:27






  • 2





    This is a better way then console.time().

    – Sanjeev
    Jan 25 '15 at 12:15



















49














If you need to get function execution time on your local development machine, you can either use your browser's profiling tools, or console commands such as console.time() and console.timeEnd().



All modern browsers have JavaScript profilers built-in. These profilers should give the most accurate measurement as you do not have to modify your existing code, which could affect the function's execution time.



To profile your JavaScript:




  • In Chrome, press F12 and select the Profiles tab, then Collect JavaScript CPU Profile.

  • In Firefox, install/open Firebug, and click on the Profile button.

  • In IE 9+, press F12, click on Script or Profiler (depending on your version of IE).


Alternatively, on your development machine, you can add instrumentation to your code with console.time() and console.timeEnd(). These functions, supported in Firefox11+, Chrome2+ and IE11+, report on timers that you start/stop via console.time(). time() takes a user-defined timer name as an argument, and timeEnd() then reports on the execution time since the timer started:



function a() {
console.time("mytimer");
... do stuff ...
var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
}


Note that only Firefox returns the elapsed time in the timeEnd() call. The other browsers simply report the result to the developer console: the return value of timeEnd() is undefined.



If you want to get function execution time in the wild, you will have to instrument your code. You have a couple options. You can simply save the start and end times by querying new Date().getTime():



function a() {
var start = new Date().getTime();
... do stuff ...
var end = new Date().getTime();
var dur = end - start;
}


However, the Date object only has millisecond resolution and will be affected by any OS's system clock changes. In modern browsers, there's a better option.



The better option is to use the High Resolution Time, aka window.performance.now(). now() is better than the traditional Date.getTime() in two important ways:




  1. now() is a double with submillisecond resolution that represents the number of milliseconds since the start of the page's navigation. It returns the number of microseconds in the fractional (e.g. a value of 1000.123 is 1 second and 123 microseconds).


  2. now() is monotonically increasing. This is important as Date.getTime() can possibly jump forward or even backward on subsequent calls. Notably, if the OS's system time is updated (e.g. atomic clock synchronization), Date.getTime() is also updated. now() is guaranteed to always be monotonically increasing, so it is not affected by the OS's system time -- it will always be wall-clock time (assuming your wall clock is not atomic...).



now() can be used in almost every place that new Date().getTime(), + new Date andt Date.now() are. The exception is that Date and now() times don't mix, as Date is based on unix-epoch (the number of milliseconds since 1970), while now() is the number of milliseconds since your page navigation started (so it will be much smaller than Date).



Here's an example of how to use now():



function a() {
var start = window.performance.now();
... do stuff ...
var end = window.performance.now();
var dur = end - start;
}


now() is supported in Chrome stable, Firefox 15+, and IE10. There are also several polyfills available.



One other option for measuring execution time in the wild is UserTiming. UserTiming behaves similarly to console.time() and console.timeEnd(), but it utilizes the same High Resolution Timestamp that now() uses (so you get a sub-millisecond monotonically increasing clock), and saves the timestamps and durations to the PerformanceTimeline.



UserTiming has the concepts of marks (timestamps) and measures (durations). You can define as many of either as you want, and they're exposed on the PerformanceTimeline.



To save a timestamp, you call mark(startMarkName). To get the duration since your first mark, you simply call measure(measurename, startMarkname). The duration is then saved in the PerformanceTimeline alongside your marks.



function a() {
window.performance.mark("start");
... do stuff ...
window.performance.measure("myfunctionduration", "start");
}

// duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];


UserTiming is available in IE10+ and Chrome25+. There is also a polyfill available (which I wrote).






share|improve this answer



















  • 1





    Excellent and most current answer IMHO :) It would be even better with a bit of editing. I'd say that user timing is not "one other option" for measuring, but the preferred option when the benchmarking is not done on the development machine itself. With your polyfill it works across all browsers. And hiding away the details and boilerplate of performance.now and Date is the reason it exists.

    – hashchange
    Jul 19 '14 at 10:10





















29














To get precise values you should use Performance interface. It's supported in modern versions of Firefox, Chrome, Opera and IE. Here's an example of how it can be used:



var performance = window.performance;
var t0 = performance.now();
doWork();
var t1 = performance.now();
console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")


Date.getTime() or console.time() are not good for measuring precise execution time. You can use them if quick rough estimate is OK for you. By rough estimate I mean you can get 15-60 ms shift from the real time.



Check this brilliant post on measuring execution time in JavaScript. The author also gives a couple of links about accuracy of JavaScript time, worth reading.






share|improve this answer

































    17














    Use Firebug, enable both Console and Javascript. Click Profile. Reload. Click Profile again. View the report.






    share|improve this answer



















    • 7





      Good advice but obviously works only for FF. We often want to compare browser speeds... :-)

      – PhiLho
      Nov 24 '08 at 11:27






    • 3





      On new Firebuq they hide this options to menu, use CTRL + SHIFT + P or console.profile(); console..profileEnd()

      – user956584
      Feb 29 '12 at 8:25






    • 3





      Chrome supports console.time() and console.timeEnd() too now.

      – julien_c
      Mar 15 '12 at 11:01



















    10














    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]');
    };


    Benchmark



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

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

    stopwatch.stop();

    stopwatch.printElapsed();


    Output



    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]


    performance.now() is optional - just pass false into StopWatch constructor function.






    share|improve this answer































      10














      process.hrtime() is available within Node.js - it returns a value in nanoseconds



      var hrTime = process.hrtime()
      console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)





      share|improve this answer


























      • if you rather convert it to ms e-3 rather than the suggested microsecond e-6: hrtime[0] * 1000 + hrtime[1] / 1000000 -> yeah, I rather use var hrtime as well! :P

        – cregox
        Mar 25 '17 at 14:21



















      7














      To extend vsync's code further to have the ability to return the timeEnd as a value in NodeJS use this little piece of code.



      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;
      };


      Now use the code like so:



      console.time('someFunction timer');

      someFunction();

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



      This gives you more possibilities. You can store the execution time to be used for more purposes like using it in equations, or stored in a database, sent to a remote client over websockets, served on a webpage, etc.






      share|improve this answer































        5














        you can use add operator also here



         var start = +new Date();
        callYourFunctionHere();
        var end = +new Date();
        var time = end - start;
        console.log('total execution time = '+ time + 'ms');





        share|improve this answer

































          4














          Since console.time and performance.now aren't supported in some major browsers (i.e. IE10), I created a slim utility that utilizes the best available methods. However, it lacks error handling for false usages (calling End() on a not initialized timer).



          Use it and improve it as you want.



          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);
          }
          }
          }





          share|improve this answer

































            4














            It may help you.



            var t0 = date.now();
            doSomething();
            var t1 = date.now();
            console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")






            share|improve this answer



















            • 1





              While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!

              – Filnor
              Mar 16 '18 at 7:09



















            3














            Thanks, Achim Koellner, will expand your answer a bit:



            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


            Please, note, that you shouldn't do anything apart from what you want to measure (for example, console.log will also take time to execute and will affect performance tests).



            Note, that in order by measure asynchronous functions execution time, you should insert var timeInMilliseconds = process.hrtime(t0)[1]/1000000; inside the callback. For example,



            var t0 = process.hrtime();
            someAsyncFunction(function(err, results) {
            var timeInMilliseconds = process.hrtime(t0)[1]/1000000;

            });





            share|improve this answer































              1














              A couple months ago I put together my own routine that times a function using Date.now() -- even though at the time the accepted method seemed to be performance.now() --
              because the performance object is not yet available (built-in) in the stable Node.js release.



              Today I was doing some more research and found another method for timing. Since I also found how to use this in Node.js code, I thought I would share it here.



              The following is combined from the examples given by w3c and Node.js:



              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)
              }


              NOTE:



              If you intend to use the performance object in a Node.js app, you must include the following require:

              const { performance } = require('perf_hooks')






              share|improve this answer

































                1














                Here's a decorator for timing functions



                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;
                }


                Usage:



                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'


                If you're using async functions you can make timed async and add an await before f(...args), and that should work for those. It gets more complicated if you want one decorator to handle both sync and async functions.






                share|improve this answer































                  0














                  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;
                  }
                  }
                  }


                  InitTime related to string.



                  return Singleton.getInstance().initTime(label); // Returns the time init



                  return Singleton.getInstance().endTime(label); // Returns the total time between init and end






                  share|improve this answer































                    0














                    If you want to measure the time between multiple things that aren't nested you could use this:



                    function timer(lap){ 
                    if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
                    timer.prev = performance.now();
                    }


                    Similar to console.time(), but easier usage if you don't need to keep track of previous timers.



                    If you like the blue color from console.time(), you can use this line instead



                    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'





                    share|improve this answer

































                      0














                      In my case, I perfer to use @ grammar suger and compile it with babel.

                      The problem of this method is that function has to be inside object.



                      Sample JS Code



                      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)


                      .babelrc (for babel 6)



                       {
                      "plugins": [
                      "transform-decorators-legacy"
                      ]
                      }





                      share|improve this answer

































                        -1














                        Stopwatch with cumulative cycles



                        Works with server and client (Node or DOM), uses the Performance API.
                        Good when you have many small cycles e.g. in a function called 1000 times that processes 1000 data objects but you want to see how each operation in this function adds up to the total.



                        So this one uses a module global (singleton) timer. Same as a class singleton pattern, just a bit simpler to use, but you need to put this in a separate e.g. stopwatch.js file.



                        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];
                        }
                        };





                        share|improve this answer































                          -2














                          As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:



                          //=-=|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}}}();


                          Compilation was a success!




                          • Original Size: 219 bytes gzipped (405 bytes uncompressed)

                          • Compiled Size: 109 bytes gzipped (187 bytes uncompressed)

                          • Saved 50.23% off the gzipped size (53.83% without gzip






                          share|improve this answer































                            -5














                            The accepted answer is wrong !



                            Since JavaScript is asynchronous, the values of the variable end of the accepted answer would be wrong.



                            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);


                            The execution of the for may be very fast so you can not see that the result is wrong. You can test it with a code doing some request :



                            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);


                            So the alert will prompt very quickly but in the console you'll see that the ajax requests are continuing.



                            Here is how you should do it : https://developer.mozilla.org/en-US/docs/Web/API/Performance.now






                            share|improve this answer



















                            • 7





                              It's not because of the for loop. A for loop will wait until the last loop until it will go on down your sourcecode. AJAX calls are async. And there are also other functions that run async. But a for loop is not executet async.

                              – Scriptlabs
                              Mar 12 '15 at 19:21













                            Your Answer






                            StackExchange.ifUsing("editor", function () {
                            StackExchange.using("externalEditor", function () {
                            StackExchange.using("snippets", function () {
                            StackExchange.snippets.init();
                            });
                            });
                            }, "code-snippets");

                            StackExchange.ready(function() {
                            var channelOptions = {
                            tags: "".split(" "),
                            id: "1"
                            };
                            initTagRenderer("".split(" "), "".split(" "), channelOptions);

                            StackExchange.using("externalEditor", function() {
                            // Have to fire editor after snippets, if snippets enabled
                            if (StackExchange.settings.snippets.snippetsEnabled) {
                            StackExchange.using("snippets", function() {
                            createEditor();
                            });
                            }
                            else {
                            createEditor();
                            }
                            });

                            function createEditor() {
                            StackExchange.prepareEditor({
                            heartbeatType: 'answer',
                            autoActivateHeartbeat: false,
                            convertImagesToLinks: true,
                            noModals: true,
                            showLowRepImageUploadWarning: true,
                            reputationToPostImages: 10,
                            bindNavPrevention: true,
                            postfix: "",
                            imageUploader: {
                            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                            allowUrls: true
                            },
                            onDemand: true,
                            discardSelector: ".discard-answer"
                            ,immediatelyShowMarkdownHelp:true
                            });


                            }
                            });














                            draft saved

                            draft discarded


















                            StackExchange.ready(
                            function () {
                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f313893%2fhow-to-measure-time-taken-by-a-function-to-execute%23new-answer', 'question_page');
                            }
                            );

                            Post as a guest















                            Required, but never shown

























                            21 Answers
                            21






                            active

                            oldest

                            votes








                            21 Answers
                            21






                            active

                            oldest

                            votes









                            active

                            oldest

                            votes






                            active

                            oldest

                            votes









                            1296














                            Using performance.now():



                            var t0 = performance.now();

                            doSomething(); // <---- The function you're measuring time for

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



                            NodeJs: it is required to import the performance class






                            Using console.time: (non-standard) (living standard)



                            console.time('someFunction');

                            someFunction(); // Whatever is timed goes between the two "console.time"

                            console.timeEnd('someFunction');


                            Note:
                            The string being pass to the time() and timeEnd() methods must match
                            (for the timer to finish as expected).





                            console.time() documentations:




                            1. NodeJS documentation regarding

                            2. MDN (client-side) documentation







                            share|improve this answer





















                            • 18





                              It's supported by Chrome Developer Tools as well now.

                              – julien_c
                              Mar 15 '12 at 11:00






                            • 3





                              This is currently the best way to collect accurate timings from what I understand.

                              – Ash Blue
                              May 5 '12 at 2:18






                            • 4





                              Don't you need to execute the function between those two statements? You now measure the time it takes to define it, not to execute it. Correct me if I'm wrong...

                              – Cristian
                              Sep 4 '12 at 22:06






                            • 2





                              Link to the MDN article about this feature: developer.mozilla.org/en-US/docs/DOM/console.time

                              – nullability
                              Feb 19 '13 at 17:19






                            • 6





                              yes you can do `totalTime += console.timeEnd('timer')' and do it for each timer

                              – vsync
                              Jun 19 '13 at 15:28
















                            1296














                            Using performance.now():



                            var t0 = performance.now();

                            doSomething(); // <---- The function you're measuring time for

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



                            NodeJs: it is required to import the performance class






                            Using console.time: (non-standard) (living standard)



                            console.time('someFunction');

                            someFunction(); // Whatever is timed goes between the two "console.time"

                            console.timeEnd('someFunction');


                            Note:
                            The string being pass to the time() and timeEnd() methods must match
                            (for the timer to finish as expected).





                            console.time() documentations:




                            1. NodeJS documentation regarding

                            2. MDN (client-side) documentation







                            share|improve this answer





















                            • 18





                              It's supported by Chrome Developer Tools as well now.

                              – julien_c
                              Mar 15 '12 at 11:00






                            • 3





                              This is currently the best way to collect accurate timings from what I understand.

                              – Ash Blue
                              May 5 '12 at 2:18






                            • 4





                              Don't you need to execute the function between those two statements? You now measure the time it takes to define it, not to execute it. Correct me if I'm wrong...

                              – Cristian
                              Sep 4 '12 at 22:06






                            • 2





                              Link to the MDN article about this feature: developer.mozilla.org/en-US/docs/DOM/console.time

                              – nullability
                              Feb 19 '13 at 17:19






                            • 6





                              yes you can do `totalTime += console.timeEnd('timer')' and do it for each timer

                              – vsync
                              Jun 19 '13 at 15:28














                            1296












                            1296








                            1296







                            Using performance.now():



                            var t0 = performance.now();

                            doSomething(); // <---- The function you're measuring time for

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



                            NodeJs: it is required to import the performance class






                            Using console.time: (non-standard) (living standard)



                            console.time('someFunction');

                            someFunction(); // Whatever is timed goes between the two "console.time"

                            console.timeEnd('someFunction');


                            Note:
                            The string being pass to the time() and timeEnd() methods must match
                            (for the timer to finish as expected).





                            console.time() documentations:




                            1. NodeJS documentation regarding

                            2. MDN (client-side) documentation







                            share|improve this answer















                            Using performance.now():



                            var t0 = performance.now();

                            doSomething(); // <---- The function you're measuring time for

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



                            NodeJs: it is required to import the performance class






                            Using console.time: (non-standard) (living standard)



                            console.time('someFunction');

                            someFunction(); // Whatever is timed goes between the two "console.time"

                            console.timeEnd('someFunction');


                            Note:
                            The string being pass to the time() and timeEnd() methods must match
                            (for the timer to finish as expected).





                            console.time() documentations:




                            1. NodeJS documentation regarding

                            2. MDN (client-side) documentation








                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 14 '18 at 12:56

























                            answered Dec 29 '09 at 15:05









                            vsyncvsync

                            46.5k36159219




                            46.5k36159219








                            • 18





                              It's supported by Chrome Developer Tools as well now.

                              – julien_c
                              Mar 15 '12 at 11:00






                            • 3





                              This is currently the best way to collect accurate timings from what I understand.

                              – Ash Blue
                              May 5 '12 at 2:18






                            • 4





                              Don't you need to execute the function between those two statements? You now measure the time it takes to define it, not to execute it. Correct me if I'm wrong...

                              – Cristian
                              Sep 4 '12 at 22:06






                            • 2





                              Link to the MDN article about this feature: developer.mozilla.org/en-US/docs/DOM/console.time

                              – nullability
                              Feb 19 '13 at 17:19






                            • 6





                              yes you can do `totalTime += console.timeEnd('timer')' and do it for each timer

                              – vsync
                              Jun 19 '13 at 15:28














                            • 18





                              It's supported by Chrome Developer Tools as well now.

                              – julien_c
                              Mar 15 '12 at 11:00






                            • 3





                              This is currently the best way to collect accurate timings from what I understand.

                              – Ash Blue
                              May 5 '12 at 2:18






                            • 4





                              Don't you need to execute the function between those two statements? You now measure the time it takes to define it, not to execute it. Correct me if I'm wrong...

                              – Cristian
                              Sep 4 '12 at 22:06






                            • 2





                              Link to the MDN article about this feature: developer.mozilla.org/en-US/docs/DOM/console.time

                              – nullability
                              Feb 19 '13 at 17:19






                            • 6





                              yes you can do `totalTime += console.timeEnd('timer')' and do it for each timer

                              – vsync
                              Jun 19 '13 at 15:28








                            18




                            18





                            It's supported by Chrome Developer Tools as well now.

                            – julien_c
                            Mar 15 '12 at 11:00





                            It's supported by Chrome Developer Tools as well now.

                            – julien_c
                            Mar 15 '12 at 11:00




                            3




                            3





                            This is currently the best way to collect accurate timings from what I understand.

                            – Ash Blue
                            May 5 '12 at 2:18





                            This is currently the best way to collect accurate timings from what I understand.

                            – Ash Blue
                            May 5 '12 at 2:18




                            4




                            4





                            Don't you need to execute the function between those two statements? You now measure the time it takes to define it, not to execute it. Correct me if I'm wrong...

                            – Cristian
                            Sep 4 '12 at 22:06





                            Don't you need to execute the function between those two statements? You now measure the time it takes to define it, not to execute it. Correct me if I'm wrong...

                            – Cristian
                            Sep 4 '12 at 22:06




                            2




                            2





                            Link to the MDN article about this feature: developer.mozilla.org/en-US/docs/DOM/console.time

                            – nullability
                            Feb 19 '13 at 17:19





                            Link to the MDN article about this feature: developer.mozilla.org/en-US/docs/DOM/console.time

                            – nullability
                            Feb 19 '13 at 17:19




                            6




                            6





                            yes you can do `totalTime += console.timeEnd('timer')' and do it for each timer

                            – vsync
                            Jun 19 '13 at 15:28





                            yes you can do `totalTime += console.timeEnd('timer')' and do it for each timer

                            – vsync
                            Jun 19 '13 at 15:28













                            584














                            use new Date().getTime()




                            The getTime() method returns the number of milliseconds since midnight of January 1, 1970.




                            ex.



                            var start = new Date().getTime();

                            for (i = 0; i < 50000; ++i) {
                            // do something
                            }

                            var end = new Date().getTime();
                            var time = end - start;
                            alert('Execution time: ' + time);





                            share|improve this answer





















                            • 9





                              Note that you can substitute +new Date() for the getTime() call: var start = +new Date(); // do stuff alert("Execution time: "+(+new Date())-start);

                              – J c
                              Nov 24 '08 at 13:00






                            • 47





                              Timings are not accurate because Date is not intended for this functionality. I'm going to be bold here and say you should use vsync's example if you want accurate timing. Although it only works in Chrome and Firefox ATM.

                              – Ash Blue
                              May 5 '12 at 2:17






                            • 9





                              Beware, the getMilliseconds() gives you the millisecond fraction of the current second. If you replace getTime() with getMilliseconds() you can get negative results if you cross a second.

                              – RickyA
                              Jan 10 '13 at 15:47






                            • 6





                              The answer by vsync is far more correct by todays standards, and using Date() can result in very erronous results being displayed, especially on the Windows platform where results may be rounded+floored to the nearest 15ms boundary, resulting in weird stuff such as 0ms timings on tiny code bits.

                              – oligofren
                              Mar 6 '13 at 9:59






                            • 28





                              @AshBlue, we should use window.performance.now. See stackoverflow.com/a/15641427/632951

                              – Pacerier
                              Nov 2 '13 at 2:17


















                            584














                            use new Date().getTime()




                            The getTime() method returns the number of milliseconds since midnight of January 1, 1970.




                            ex.



                            var start = new Date().getTime();

                            for (i = 0; i < 50000; ++i) {
                            // do something
                            }

                            var end = new Date().getTime();
                            var time = end - start;
                            alert('Execution time: ' + time);





                            share|improve this answer





















                            • 9





                              Note that you can substitute +new Date() for the getTime() call: var start = +new Date(); // do stuff alert("Execution time: "+(+new Date())-start);

                              – J c
                              Nov 24 '08 at 13:00






                            • 47





                              Timings are not accurate because Date is not intended for this functionality. I'm going to be bold here and say you should use vsync's example if you want accurate timing. Although it only works in Chrome and Firefox ATM.

                              – Ash Blue
                              May 5 '12 at 2:17






                            • 9





                              Beware, the getMilliseconds() gives you the millisecond fraction of the current second. If you replace getTime() with getMilliseconds() you can get negative results if you cross a second.

                              – RickyA
                              Jan 10 '13 at 15:47






                            • 6





                              The answer by vsync is far more correct by todays standards, and using Date() can result in very erronous results being displayed, especially on the Windows platform where results may be rounded+floored to the nearest 15ms boundary, resulting in weird stuff such as 0ms timings on tiny code bits.

                              – oligofren
                              Mar 6 '13 at 9:59






                            • 28





                              @AshBlue, we should use window.performance.now. See stackoverflow.com/a/15641427/632951

                              – Pacerier
                              Nov 2 '13 at 2:17
















                            584












                            584








                            584







                            use new Date().getTime()




                            The getTime() method returns the number of milliseconds since midnight of January 1, 1970.




                            ex.



                            var start = new Date().getTime();

                            for (i = 0; i < 50000; ++i) {
                            // do something
                            }

                            var end = new Date().getTime();
                            var time = end - start;
                            alert('Execution time: ' + time);





                            share|improve this answer















                            use new Date().getTime()




                            The getTime() method returns the number of milliseconds since midnight of January 1, 1970.




                            ex.



                            var start = new Date().getTime();

                            for (i = 0; i < 50000; ++i) {
                            // do something
                            }

                            var end = new Date().getTime();
                            var time = end - start;
                            alert('Execution time: ' + time);






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Apr 12 '16 at 4:17









                            Sam Watkins

                            4,57522528




                            4,57522528










                            answered Nov 24 '08 at 11:15









                            OwenOwen

                            64.8k18104112




                            64.8k18104112








                            • 9





                              Note that you can substitute +new Date() for the getTime() call: var start = +new Date(); // do stuff alert("Execution time: "+(+new Date())-start);

                              – J c
                              Nov 24 '08 at 13:00






                            • 47





                              Timings are not accurate because Date is not intended for this functionality. I'm going to be bold here and say you should use vsync's example if you want accurate timing. Although it only works in Chrome and Firefox ATM.

                              – Ash Blue
                              May 5 '12 at 2:17






                            • 9





                              Beware, the getMilliseconds() gives you the millisecond fraction of the current second. If you replace getTime() with getMilliseconds() you can get negative results if you cross a second.

                              – RickyA
                              Jan 10 '13 at 15:47






                            • 6





                              The answer by vsync is far more correct by todays standards, and using Date() can result in very erronous results being displayed, especially on the Windows platform where results may be rounded+floored to the nearest 15ms boundary, resulting in weird stuff such as 0ms timings on tiny code bits.

                              – oligofren
                              Mar 6 '13 at 9:59






                            • 28





                              @AshBlue, we should use window.performance.now. See stackoverflow.com/a/15641427/632951

                              – Pacerier
                              Nov 2 '13 at 2:17
















                            • 9





                              Note that you can substitute +new Date() for the getTime() call: var start = +new Date(); // do stuff alert("Execution time: "+(+new Date())-start);

                              – J c
                              Nov 24 '08 at 13:00






                            • 47





                              Timings are not accurate because Date is not intended for this functionality. I'm going to be bold here and say you should use vsync's example if you want accurate timing. Although it only works in Chrome and Firefox ATM.

                              – Ash Blue
                              May 5 '12 at 2:17






                            • 9





                              Beware, the getMilliseconds() gives you the millisecond fraction of the current second. If you replace getTime() with getMilliseconds() you can get negative results if you cross a second.

                              – RickyA
                              Jan 10 '13 at 15:47






                            • 6





                              The answer by vsync is far more correct by todays standards, and using Date() can result in very erronous results being displayed, especially on the Windows platform where results may be rounded+floored to the nearest 15ms boundary, resulting in weird stuff such as 0ms timings on tiny code bits.

                              – oligofren
                              Mar 6 '13 at 9:59






                            • 28





                              @AshBlue, we should use window.performance.now. See stackoverflow.com/a/15641427/632951

                              – Pacerier
                              Nov 2 '13 at 2:17










                            9




                            9





                            Note that you can substitute +new Date() for the getTime() call: var start = +new Date(); // do stuff alert("Execution time: "+(+new Date())-start);

                            – J c
                            Nov 24 '08 at 13:00





                            Note that you can substitute +new Date() for the getTime() call: var start = +new Date(); // do stuff alert("Execution time: "+(+new Date())-start);

                            – J c
                            Nov 24 '08 at 13:00




                            47




                            47





                            Timings are not accurate because Date is not intended for this functionality. I'm going to be bold here and say you should use vsync's example if you want accurate timing. Although it only works in Chrome and Firefox ATM.

                            – Ash Blue
                            May 5 '12 at 2:17





                            Timings are not accurate because Date is not intended for this functionality. I'm going to be bold here and say you should use vsync's example if you want accurate timing. Although it only works in Chrome and Firefox ATM.

                            – Ash Blue
                            May 5 '12 at 2:17




                            9




                            9





                            Beware, the getMilliseconds() gives you the millisecond fraction of the current second. If you replace getTime() with getMilliseconds() you can get negative results if you cross a second.

                            – RickyA
                            Jan 10 '13 at 15:47





                            Beware, the getMilliseconds() gives you the millisecond fraction of the current second. If you replace getTime() with getMilliseconds() you can get negative results if you cross a second.

                            – RickyA
                            Jan 10 '13 at 15:47




                            6




                            6





                            The answer by vsync is far more correct by todays standards, and using Date() can result in very erronous results being displayed, especially on the Windows platform where results may be rounded+floored to the nearest 15ms boundary, resulting in weird stuff such as 0ms timings on tiny code bits.

                            – oligofren
                            Mar 6 '13 at 9:59





                            The answer by vsync is far more correct by todays standards, and using Date() can result in very erronous results being displayed, especially on the Windows platform where results may be rounded+floored to the nearest 15ms boundary, resulting in weird stuff such as 0ms timings on tiny code bits.

                            – oligofren
                            Mar 6 '13 at 9:59




                            28




                            28





                            @AshBlue, we should use window.performance.now. See stackoverflow.com/a/15641427/632951

                            – Pacerier
                            Nov 2 '13 at 2:17







                            @AshBlue, we should use window.performance.now. See stackoverflow.com/a/15641427/632951

                            – Pacerier
                            Nov 2 '13 at 2:17













                            382














                            Don't use Date(). Read below.



                            Use performance.now():



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


                            It works on:




                            • IE 10 ++


                            • FireFox 15 ++


                            • Chrome 24 ++


                            • Safari 8 ++


                            • Opera 15 ++


                            • Android 4.4 ++


                            • etc, etc



                            console.time may be viable for you, but it's non-standard §:




                            This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.




                            Besides browser support, performance.now seems to have the potential to provide more accurate timings as it appears to be the bare-bones version of console.time.





                            <rant> Also, DON'T EVER use Date for anything because it's affected by changes in "system time". Which means we will get invalid results —like "negative timing"— when the user doesn't have an accurate system time:




                            On Oct 2014, my system clock went haywire and guess what.... I opened Gmail and saw all of my day's emails "sent 0 minutes ago". And I'd thought Gmail is supposed to be built by world-class engineers from Google.......




                            (Set your system clock to one year ago and go to Gmail so we can all have a good laugh. Perhaps someday we will have a Hall of Shame for JS Date.)



                            Google Spreadsheet's now() function also suffers from this problem.



                            The only time you'll be using Date is when you want to show the user his system clock time. Not when you want to get the time or to measure anything.






                            share|improve this answer





















                            • 3





                              Just what I was looking for! I want to be able to add several times together, can't really do that with console times.

                              – Ray
                              Sep 29 '13 at 13:33






                            • 6





                              note that this isn't supported in safari yet: developer.mozilla.org/en-US/docs/Web/API/Performance.now()

                              – Akos K
                              Nov 1 '13 at 21:11






                            • 2





                              I use Firebug Profile and performance.now(), and they both work well. Performance.now() confirms my result from Profile.

                              – Vincent Jia
                              Feb 11 '14 at 10:01






                            • 2





                              Doesn't work in my biggest hangup, which is IE7 (corporate customers.) I don't care about measuring performance in chrome, it's always lightning fast.

                              – Nick
                              Mar 3 '14 at 18:27






                            • 2





                              This is a better way then console.time().

                              – Sanjeev
                              Jan 25 '15 at 12:15
















                            382














                            Don't use Date(). Read below.



                            Use performance.now():



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


                            It works on:




                            • IE 10 ++


                            • FireFox 15 ++


                            • Chrome 24 ++


                            • Safari 8 ++


                            • Opera 15 ++


                            • Android 4.4 ++


                            • etc, etc



                            console.time may be viable for you, but it's non-standard §:




                            This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.




                            Besides browser support, performance.now seems to have the potential to provide more accurate timings as it appears to be the bare-bones version of console.time.





                            <rant> Also, DON'T EVER use Date for anything because it's affected by changes in "system time". Which means we will get invalid results —like "negative timing"— when the user doesn't have an accurate system time:




                            On Oct 2014, my system clock went haywire and guess what.... I opened Gmail and saw all of my day's emails "sent 0 minutes ago". And I'd thought Gmail is supposed to be built by world-class engineers from Google.......




                            (Set your system clock to one year ago and go to Gmail so we can all have a good laugh. Perhaps someday we will have a Hall of Shame for JS Date.)



                            Google Spreadsheet's now() function also suffers from this problem.



                            The only time you'll be using Date is when you want to show the user his system clock time. Not when you want to get the time or to measure anything.






                            share|improve this answer





















                            • 3





                              Just what I was looking for! I want to be able to add several times together, can't really do that with console times.

                              – Ray
                              Sep 29 '13 at 13:33






                            • 6





                              note that this isn't supported in safari yet: developer.mozilla.org/en-US/docs/Web/API/Performance.now()

                              – Akos K
                              Nov 1 '13 at 21:11






                            • 2





                              I use Firebug Profile and performance.now(), and they both work well. Performance.now() confirms my result from Profile.

                              – Vincent Jia
                              Feb 11 '14 at 10:01






                            • 2





                              Doesn't work in my biggest hangup, which is IE7 (corporate customers.) I don't care about measuring performance in chrome, it's always lightning fast.

                              – Nick
                              Mar 3 '14 at 18:27






                            • 2





                              This is a better way then console.time().

                              – Sanjeev
                              Jan 25 '15 at 12:15














                            382












                            382








                            382







                            Don't use Date(). Read below.



                            Use performance.now():



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


                            It works on:




                            • IE 10 ++


                            • FireFox 15 ++


                            • Chrome 24 ++


                            • Safari 8 ++


                            • Opera 15 ++


                            • Android 4.4 ++


                            • etc, etc



                            console.time may be viable for you, but it's non-standard §:




                            This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.




                            Besides browser support, performance.now seems to have the potential to provide more accurate timings as it appears to be the bare-bones version of console.time.





                            <rant> Also, DON'T EVER use Date for anything because it's affected by changes in "system time". Which means we will get invalid results —like "negative timing"— when the user doesn't have an accurate system time:




                            On Oct 2014, my system clock went haywire and guess what.... I opened Gmail and saw all of my day's emails "sent 0 minutes ago". And I'd thought Gmail is supposed to be built by world-class engineers from Google.......




                            (Set your system clock to one year ago and go to Gmail so we can all have a good laugh. Perhaps someday we will have a Hall of Shame for JS Date.)



                            Google Spreadsheet's now() function also suffers from this problem.



                            The only time you'll be using Date is when you want to show the user his system clock time. Not when you want to get the time or to measure anything.






                            share|improve this answer















                            Don't use Date(). Read below.



                            Use performance.now():



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


                            It works on:




                            • IE 10 ++


                            • FireFox 15 ++


                            • Chrome 24 ++


                            • Safari 8 ++


                            • Opera 15 ++


                            • Android 4.4 ++


                            • etc, etc



                            console.time may be viable for you, but it's non-standard §:




                            This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.




                            Besides browser support, performance.now seems to have the potential to provide more accurate timings as it appears to be the bare-bones version of console.time.





                            <rant> Also, DON'T EVER use Date for anything because it's affected by changes in "system time". Which means we will get invalid results —like "negative timing"— when the user doesn't have an accurate system time:




                            On Oct 2014, my system clock went haywire and guess what.... I opened Gmail and saw all of my day's emails "sent 0 minutes ago". And I'd thought Gmail is supposed to be built by world-class engineers from Google.......




                            (Set your system clock to one year ago and go to Gmail so we can all have a good laugh. Perhaps someday we will have a Hall of Shame for JS Date.)



                            Google Spreadsheet's now() function also suffers from this problem.



                            The only time you'll be using Date is when you want to show the user his system clock time. Not when you want to get the time or to measure anything.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 20 '14 at 17:55

























                            answered Mar 26 '13 at 15:49









                            PacerierPacerier

                            44.1k51213517




                            44.1k51213517








                            • 3





                              Just what I was looking for! I want to be able to add several times together, can't really do that with console times.

                              – Ray
                              Sep 29 '13 at 13:33






                            • 6





                              note that this isn't supported in safari yet: developer.mozilla.org/en-US/docs/Web/API/Performance.now()

                              – Akos K
                              Nov 1 '13 at 21:11






                            • 2





                              I use Firebug Profile and performance.now(), and they both work well. Performance.now() confirms my result from Profile.

                              – Vincent Jia
                              Feb 11 '14 at 10:01






                            • 2





                              Doesn't work in my biggest hangup, which is IE7 (corporate customers.) I don't care about measuring performance in chrome, it's always lightning fast.

                              – Nick
                              Mar 3 '14 at 18:27






                            • 2





                              This is a better way then console.time().

                              – Sanjeev
                              Jan 25 '15 at 12:15














                            • 3





                              Just what I was looking for! I want to be able to add several times together, can't really do that with console times.

                              – Ray
                              Sep 29 '13 at 13:33






                            • 6





                              note that this isn't supported in safari yet: developer.mozilla.org/en-US/docs/Web/API/Performance.now()

                              – Akos K
                              Nov 1 '13 at 21:11






                            • 2





                              I use Firebug Profile and performance.now(), and they both work well. Performance.now() confirms my result from Profile.

                              – Vincent Jia
                              Feb 11 '14 at 10:01






                            • 2





                              Doesn't work in my biggest hangup, which is IE7 (corporate customers.) I don't care about measuring performance in chrome, it's always lightning fast.

                              – Nick
                              Mar 3 '14 at 18:27






                            • 2





                              This is a better way then console.time().

                              – Sanjeev
                              Jan 25 '15 at 12:15








                            3




                            3





                            Just what I was looking for! I want to be able to add several times together, can't really do that with console times.

                            – Ray
                            Sep 29 '13 at 13:33





                            Just what I was looking for! I want to be able to add several times together, can't really do that with console times.

                            – Ray
                            Sep 29 '13 at 13:33




                            6




                            6





                            note that this isn't supported in safari yet: developer.mozilla.org/en-US/docs/Web/API/Performance.now()

                            – Akos K
                            Nov 1 '13 at 21:11





                            note that this isn't supported in safari yet: developer.mozilla.org/en-US/docs/Web/API/Performance.now()

                            – Akos K
                            Nov 1 '13 at 21:11




                            2




                            2





                            I use Firebug Profile and performance.now(), and they both work well. Performance.now() confirms my result from Profile.

                            – Vincent Jia
                            Feb 11 '14 at 10:01





                            I use Firebug Profile and performance.now(), and they both work well. Performance.now() confirms my result from Profile.

                            – Vincent Jia
                            Feb 11 '14 at 10:01




                            2




                            2





                            Doesn't work in my biggest hangup, which is IE7 (corporate customers.) I don't care about measuring performance in chrome, it's always lightning fast.

                            – Nick
                            Mar 3 '14 at 18:27





                            Doesn't work in my biggest hangup, which is IE7 (corporate customers.) I don't care about measuring performance in chrome, it's always lightning fast.

                            – Nick
                            Mar 3 '14 at 18:27




                            2




                            2





                            This is a better way then console.time().

                            – Sanjeev
                            Jan 25 '15 at 12:15





                            This is a better way then console.time().

                            – Sanjeev
                            Jan 25 '15 at 12:15











                            49














                            If you need to get function execution time on your local development machine, you can either use your browser's profiling tools, or console commands such as console.time() and console.timeEnd().



                            All modern browsers have JavaScript profilers built-in. These profilers should give the most accurate measurement as you do not have to modify your existing code, which could affect the function's execution time.



                            To profile your JavaScript:




                            • In Chrome, press F12 and select the Profiles tab, then Collect JavaScript CPU Profile.

                            • In Firefox, install/open Firebug, and click on the Profile button.

                            • In IE 9+, press F12, click on Script or Profiler (depending on your version of IE).


                            Alternatively, on your development machine, you can add instrumentation to your code with console.time() and console.timeEnd(). These functions, supported in Firefox11+, Chrome2+ and IE11+, report on timers that you start/stop via console.time(). time() takes a user-defined timer name as an argument, and timeEnd() then reports on the execution time since the timer started:



                            function a() {
                            console.time("mytimer");
                            ... do stuff ...
                            var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
                            }


                            Note that only Firefox returns the elapsed time in the timeEnd() call. The other browsers simply report the result to the developer console: the return value of timeEnd() is undefined.



                            If you want to get function execution time in the wild, you will have to instrument your code. You have a couple options. You can simply save the start and end times by querying new Date().getTime():



                            function a() {
                            var start = new Date().getTime();
                            ... do stuff ...
                            var end = new Date().getTime();
                            var dur = end - start;
                            }


                            However, the Date object only has millisecond resolution and will be affected by any OS's system clock changes. In modern browsers, there's a better option.



                            The better option is to use the High Resolution Time, aka window.performance.now(). now() is better than the traditional Date.getTime() in two important ways:




                            1. now() is a double with submillisecond resolution that represents the number of milliseconds since the start of the page's navigation. It returns the number of microseconds in the fractional (e.g. a value of 1000.123 is 1 second and 123 microseconds).


                            2. now() is monotonically increasing. This is important as Date.getTime() can possibly jump forward or even backward on subsequent calls. Notably, if the OS's system time is updated (e.g. atomic clock synchronization), Date.getTime() is also updated. now() is guaranteed to always be monotonically increasing, so it is not affected by the OS's system time -- it will always be wall-clock time (assuming your wall clock is not atomic...).



                            now() can be used in almost every place that new Date().getTime(), + new Date andt Date.now() are. The exception is that Date and now() times don't mix, as Date is based on unix-epoch (the number of milliseconds since 1970), while now() is the number of milliseconds since your page navigation started (so it will be much smaller than Date).



                            Here's an example of how to use now():



                            function a() {
                            var start = window.performance.now();
                            ... do stuff ...
                            var end = window.performance.now();
                            var dur = end - start;
                            }


                            now() is supported in Chrome stable, Firefox 15+, and IE10. There are also several polyfills available.



                            One other option for measuring execution time in the wild is UserTiming. UserTiming behaves similarly to console.time() and console.timeEnd(), but it utilizes the same High Resolution Timestamp that now() uses (so you get a sub-millisecond monotonically increasing clock), and saves the timestamps and durations to the PerformanceTimeline.



                            UserTiming has the concepts of marks (timestamps) and measures (durations). You can define as many of either as you want, and they're exposed on the PerformanceTimeline.



                            To save a timestamp, you call mark(startMarkName). To get the duration since your first mark, you simply call measure(measurename, startMarkname). The duration is then saved in the PerformanceTimeline alongside your marks.



                            function a() {
                            window.performance.mark("start");
                            ... do stuff ...
                            window.performance.measure("myfunctionduration", "start");
                            }

                            // duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];


                            UserTiming is available in IE10+ and Chrome25+. There is also a polyfill available (which I wrote).






                            share|improve this answer



















                            • 1





                              Excellent and most current answer IMHO :) It would be even better with a bit of editing. I'd say that user timing is not "one other option" for measuring, but the preferred option when the benchmarking is not done on the development machine itself. With your polyfill it works across all browsers. And hiding away the details and boilerplate of performance.now and Date is the reason it exists.

                              – hashchange
                              Jul 19 '14 at 10:10


















                            49














                            If you need to get function execution time on your local development machine, you can either use your browser's profiling tools, or console commands such as console.time() and console.timeEnd().



                            All modern browsers have JavaScript profilers built-in. These profilers should give the most accurate measurement as you do not have to modify your existing code, which could affect the function's execution time.



                            To profile your JavaScript:




                            • In Chrome, press F12 and select the Profiles tab, then Collect JavaScript CPU Profile.

                            • In Firefox, install/open Firebug, and click on the Profile button.

                            • In IE 9+, press F12, click on Script or Profiler (depending on your version of IE).


                            Alternatively, on your development machine, you can add instrumentation to your code with console.time() and console.timeEnd(). These functions, supported in Firefox11+, Chrome2+ and IE11+, report on timers that you start/stop via console.time(). time() takes a user-defined timer name as an argument, and timeEnd() then reports on the execution time since the timer started:



                            function a() {
                            console.time("mytimer");
                            ... do stuff ...
                            var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
                            }


                            Note that only Firefox returns the elapsed time in the timeEnd() call. The other browsers simply report the result to the developer console: the return value of timeEnd() is undefined.



                            If you want to get function execution time in the wild, you will have to instrument your code. You have a couple options. You can simply save the start and end times by querying new Date().getTime():



                            function a() {
                            var start = new Date().getTime();
                            ... do stuff ...
                            var end = new Date().getTime();
                            var dur = end - start;
                            }


                            However, the Date object only has millisecond resolution and will be affected by any OS's system clock changes. In modern browsers, there's a better option.



                            The better option is to use the High Resolution Time, aka window.performance.now(). now() is better than the traditional Date.getTime() in two important ways:




                            1. now() is a double with submillisecond resolution that represents the number of milliseconds since the start of the page's navigation. It returns the number of microseconds in the fractional (e.g. a value of 1000.123 is 1 second and 123 microseconds).


                            2. now() is monotonically increasing. This is important as Date.getTime() can possibly jump forward or even backward on subsequent calls. Notably, if the OS's system time is updated (e.g. atomic clock synchronization), Date.getTime() is also updated. now() is guaranteed to always be monotonically increasing, so it is not affected by the OS's system time -- it will always be wall-clock time (assuming your wall clock is not atomic...).



                            now() can be used in almost every place that new Date().getTime(), + new Date andt Date.now() are. The exception is that Date and now() times don't mix, as Date is based on unix-epoch (the number of milliseconds since 1970), while now() is the number of milliseconds since your page navigation started (so it will be much smaller than Date).



                            Here's an example of how to use now():



                            function a() {
                            var start = window.performance.now();
                            ... do stuff ...
                            var end = window.performance.now();
                            var dur = end - start;
                            }


                            now() is supported in Chrome stable, Firefox 15+, and IE10. There are also several polyfills available.



                            One other option for measuring execution time in the wild is UserTiming. UserTiming behaves similarly to console.time() and console.timeEnd(), but it utilizes the same High Resolution Timestamp that now() uses (so you get a sub-millisecond monotonically increasing clock), and saves the timestamps and durations to the PerformanceTimeline.



                            UserTiming has the concepts of marks (timestamps) and measures (durations). You can define as many of either as you want, and they're exposed on the PerformanceTimeline.



                            To save a timestamp, you call mark(startMarkName). To get the duration since your first mark, you simply call measure(measurename, startMarkname). The duration is then saved in the PerformanceTimeline alongside your marks.



                            function a() {
                            window.performance.mark("start");
                            ... do stuff ...
                            window.performance.measure("myfunctionduration", "start");
                            }

                            // duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];


                            UserTiming is available in IE10+ and Chrome25+. There is also a polyfill available (which I wrote).






                            share|improve this answer



















                            • 1





                              Excellent and most current answer IMHO :) It would be even better with a bit of editing. I'd say that user timing is not "one other option" for measuring, but the preferred option when the benchmarking is not done on the development machine itself. With your polyfill it works across all browsers. And hiding away the details and boilerplate of performance.now and Date is the reason it exists.

                              – hashchange
                              Jul 19 '14 at 10:10
















                            49












                            49








                            49







                            If you need to get function execution time on your local development machine, you can either use your browser's profiling tools, or console commands such as console.time() and console.timeEnd().



                            All modern browsers have JavaScript profilers built-in. These profilers should give the most accurate measurement as you do not have to modify your existing code, which could affect the function's execution time.



                            To profile your JavaScript:




                            • In Chrome, press F12 and select the Profiles tab, then Collect JavaScript CPU Profile.

                            • In Firefox, install/open Firebug, and click on the Profile button.

                            • In IE 9+, press F12, click on Script or Profiler (depending on your version of IE).


                            Alternatively, on your development machine, you can add instrumentation to your code with console.time() and console.timeEnd(). These functions, supported in Firefox11+, Chrome2+ and IE11+, report on timers that you start/stop via console.time(). time() takes a user-defined timer name as an argument, and timeEnd() then reports on the execution time since the timer started:



                            function a() {
                            console.time("mytimer");
                            ... do stuff ...
                            var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
                            }


                            Note that only Firefox returns the elapsed time in the timeEnd() call. The other browsers simply report the result to the developer console: the return value of timeEnd() is undefined.



                            If you want to get function execution time in the wild, you will have to instrument your code. You have a couple options. You can simply save the start and end times by querying new Date().getTime():



                            function a() {
                            var start = new Date().getTime();
                            ... do stuff ...
                            var end = new Date().getTime();
                            var dur = end - start;
                            }


                            However, the Date object only has millisecond resolution and will be affected by any OS's system clock changes. In modern browsers, there's a better option.



                            The better option is to use the High Resolution Time, aka window.performance.now(). now() is better than the traditional Date.getTime() in two important ways:




                            1. now() is a double with submillisecond resolution that represents the number of milliseconds since the start of the page's navigation. It returns the number of microseconds in the fractional (e.g. a value of 1000.123 is 1 second and 123 microseconds).


                            2. now() is monotonically increasing. This is important as Date.getTime() can possibly jump forward or even backward on subsequent calls. Notably, if the OS's system time is updated (e.g. atomic clock synchronization), Date.getTime() is also updated. now() is guaranteed to always be monotonically increasing, so it is not affected by the OS's system time -- it will always be wall-clock time (assuming your wall clock is not atomic...).



                            now() can be used in almost every place that new Date().getTime(), + new Date andt Date.now() are. The exception is that Date and now() times don't mix, as Date is based on unix-epoch (the number of milliseconds since 1970), while now() is the number of milliseconds since your page navigation started (so it will be much smaller than Date).



                            Here's an example of how to use now():



                            function a() {
                            var start = window.performance.now();
                            ... do stuff ...
                            var end = window.performance.now();
                            var dur = end - start;
                            }


                            now() is supported in Chrome stable, Firefox 15+, and IE10. There are also several polyfills available.



                            One other option for measuring execution time in the wild is UserTiming. UserTiming behaves similarly to console.time() and console.timeEnd(), but it utilizes the same High Resolution Timestamp that now() uses (so you get a sub-millisecond monotonically increasing clock), and saves the timestamps and durations to the PerformanceTimeline.



                            UserTiming has the concepts of marks (timestamps) and measures (durations). You can define as many of either as you want, and they're exposed on the PerformanceTimeline.



                            To save a timestamp, you call mark(startMarkName). To get the duration since your first mark, you simply call measure(measurename, startMarkname). The duration is then saved in the PerformanceTimeline alongside your marks.



                            function a() {
                            window.performance.mark("start");
                            ... do stuff ...
                            window.performance.measure("myfunctionduration", "start");
                            }

                            // duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];


                            UserTiming is available in IE10+ and Chrome25+. There is also a polyfill available (which I wrote).






                            share|improve this answer













                            If you need to get function execution time on your local development machine, you can either use your browser's profiling tools, or console commands such as console.time() and console.timeEnd().



                            All modern browsers have JavaScript profilers built-in. These profilers should give the most accurate measurement as you do not have to modify your existing code, which could affect the function's execution time.



                            To profile your JavaScript:




                            • In Chrome, press F12 and select the Profiles tab, then Collect JavaScript CPU Profile.

                            • In Firefox, install/open Firebug, and click on the Profile button.

                            • In IE 9+, press F12, click on Script or Profiler (depending on your version of IE).


                            Alternatively, on your development machine, you can add instrumentation to your code with console.time() and console.timeEnd(). These functions, supported in Firefox11+, Chrome2+ and IE11+, report on timers that you start/stop via console.time(). time() takes a user-defined timer name as an argument, and timeEnd() then reports on the execution time since the timer started:



                            function a() {
                            console.time("mytimer");
                            ... do stuff ...
                            var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
                            }


                            Note that only Firefox returns the elapsed time in the timeEnd() call. The other browsers simply report the result to the developer console: the return value of timeEnd() is undefined.



                            If you want to get function execution time in the wild, you will have to instrument your code. You have a couple options. You can simply save the start and end times by querying new Date().getTime():



                            function a() {
                            var start = new Date().getTime();
                            ... do stuff ...
                            var end = new Date().getTime();
                            var dur = end - start;
                            }


                            However, the Date object only has millisecond resolution and will be affected by any OS's system clock changes. In modern browsers, there's a better option.



                            The better option is to use the High Resolution Time, aka window.performance.now(). now() is better than the traditional Date.getTime() in two important ways:




                            1. now() is a double with submillisecond resolution that represents the number of milliseconds since the start of the page's navigation. It returns the number of microseconds in the fractional (e.g. a value of 1000.123 is 1 second and 123 microseconds).


                            2. now() is monotonically increasing. This is important as Date.getTime() can possibly jump forward or even backward on subsequent calls. Notably, if the OS's system time is updated (e.g. atomic clock synchronization), Date.getTime() is also updated. now() is guaranteed to always be monotonically increasing, so it is not affected by the OS's system time -- it will always be wall-clock time (assuming your wall clock is not atomic...).



                            now() can be used in almost every place that new Date().getTime(), + new Date andt Date.now() are. The exception is that Date and now() times don't mix, as Date is based on unix-epoch (the number of milliseconds since 1970), while now() is the number of milliseconds since your page navigation started (so it will be much smaller than Date).



                            Here's an example of how to use now():



                            function a() {
                            var start = window.performance.now();
                            ... do stuff ...
                            var end = window.performance.now();
                            var dur = end - start;
                            }


                            now() is supported in Chrome stable, Firefox 15+, and IE10. There are also several polyfills available.



                            One other option for measuring execution time in the wild is UserTiming. UserTiming behaves similarly to console.time() and console.timeEnd(), but it utilizes the same High Resolution Timestamp that now() uses (so you get a sub-millisecond monotonically increasing clock), and saves the timestamps and durations to the PerformanceTimeline.



                            UserTiming has the concepts of marks (timestamps) and measures (durations). You can define as many of either as you want, and they're exposed on the PerformanceTimeline.



                            To save a timestamp, you call mark(startMarkName). To get the duration since your first mark, you simply call measure(measurename, startMarkname). The duration is then saved in the PerformanceTimeline alongside your marks.



                            function a() {
                            window.performance.mark("start");
                            ... do stuff ...
                            window.performance.measure("myfunctionduration", "start");
                            }

                            // duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];


                            UserTiming is available in IE10+ and Chrome25+. There is also a polyfill available (which I wrote).







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 14 '14 at 19:01









                            NicJNicJ

                            3,16212018




                            3,16212018








                            • 1





                              Excellent and most current answer IMHO :) It would be even better with a bit of editing. I'd say that user timing is not "one other option" for measuring, but the preferred option when the benchmarking is not done on the development machine itself. With your polyfill it works across all browsers. And hiding away the details and boilerplate of performance.now and Date is the reason it exists.

                              – hashchange
                              Jul 19 '14 at 10:10
















                            • 1





                              Excellent and most current answer IMHO :) It would be even better with a bit of editing. I'd say that user timing is not "one other option" for measuring, but the preferred option when the benchmarking is not done on the development machine itself. With your polyfill it works across all browsers. And hiding away the details and boilerplate of performance.now and Date is the reason it exists.

                              – hashchange
                              Jul 19 '14 at 10:10










                            1




                            1





                            Excellent and most current answer IMHO :) It would be even better with a bit of editing. I'd say that user timing is not "one other option" for measuring, but the preferred option when the benchmarking is not done on the development machine itself. With your polyfill it works across all browsers. And hiding away the details and boilerplate of performance.now and Date is the reason it exists.

                            – hashchange
                            Jul 19 '14 at 10:10







                            Excellent and most current answer IMHO :) It would be even better with a bit of editing. I'd say that user timing is not "one other option" for measuring, but the preferred option when the benchmarking is not done on the development machine itself. With your polyfill it works across all browsers. And hiding away the details and boilerplate of performance.now and Date is the reason it exists.

                            – hashchange
                            Jul 19 '14 at 10:10













                            29














                            To get precise values you should use Performance interface. It's supported in modern versions of Firefox, Chrome, Opera and IE. Here's an example of how it can be used:



                            var performance = window.performance;
                            var t0 = performance.now();
                            doWork();
                            var t1 = performance.now();
                            console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")


                            Date.getTime() or console.time() are not good for measuring precise execution time. You can use them if quick rough estimate is OK for you. By rough estimate I mean you can get 15-60 ms shift from the real time.



                            Check this brilliant post on measuring execution time in JavaScript. The author also gives a couple of links about accuracy of JavaScript time, worth reading.






                            share|improve this answer






























                              29














                              To get precise values you should use Performance interface. It's supported in modern versions of Firefox, Chrome, Opera and IE. Here's an example of how it can be used:



                              var performance = window.performance;
                              var t0 = performance.now();
                              doWork();
                              var t1 = performance.now();
                              console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")


                              Date.getTime() or console.time() are not good for measuring precise execution time. You can use them if quick rough estimate is OK for you. By rough estimate I mean you can get 15-60 ms shift from the real time.



                              Check this brilliant post on measuring execution time in JavaScript. The author also gives a couple of links about accuracy of JavaScript time, worth reading.






                              share|improve this answer




























                                29












                                29








                                29







                                To get precise values you should use Performance interface. It's supported in modern versions of Firefox, Chrome, Opera and IE. Here's an example of how it can be used:



                                var performance = window.performance;
                                var t0 = performance.now();
                                doWork();
                                var t1 = performance.now();
                                console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")


                                Date.getTime() or console.time() are not good for measuring precise execution time. You can use them if quick rough estimate is OK for you. By rough estimate I mean you can get 15-60 ms shift from the real time.



                                Check this brilliant post on measuring execution time in JavaScript. The author also gives a couple of links about accuracy of JavaScript time, worth reading.






                                share|improve this answer















                                To get precise values you should use Performance interface. It's supported in modern versions of Firefox, Chrome, Opera and IE. Here's an example of how it can be used:



                                var performance = window.performance;
                                var t0 = performance.now();
                                doWork();
                                var t1 = performance.now();
                                console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")


                                Date.getTime() or console.time() are not good for measuring precise execution time. You can use them if quick rough estimate is OK for you. By rough estimate I mean you can get 15-60 ms shift from the real time.



                                Check this brilliant post on measuring execution time in JavaScript. The author also gives a couple of links about accuracy of JavaScript time, worth reading.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Oct 6 '16 at 21:11









                                Aaron Hudon

                                1,91912533




                                1,91912533










                                answered Feb 26 '15 at 16:13









                                Varvara KalininaVarvara Kalinina

                                1,3561123




                                1,3561123























                                    17














                                    Use Firebug, enable both Console and Javascript. Click Profile. Reload. Click Profile again. View the report.






                                    share|improve this answer



















                                    • 7





                                      Good advice but obviously works only for FF. We often want to compare browser speeds... :-)

                                      – PhiLho
                                      Nov 24 '08 at 11:27






                                    • 3





                                      On new Firebuq they hide this options to menu, use CTRL + SHIFT + P or console.profile(); console..profileEnd()

                                      – user956584
                                      Feb 29 '12 at 8:25






                                    • 3





                                      Chrome supports console.time() and console.timeEnd() too now.

                                      – julien_c
                                      Mar 15 '12 at 11:01
















                                    17














                                    Use Firebug, enable both Console and Javascript. Click Profile. Reload. Click Profile again. View the report.






                                    share|improve this answer



















                                    • 7





                                      Good advice but obviously works only for FF. We often want to compare browser speeds... :-)

                                      – PhiLho
                                      Nov 24 '08 at 11:27






                                    • 3





                                      On new Firebuq they hide this options to menu, use CTRL + SHIFT + P or console.profile(); console..profileEnd()

                                      – user956584
                                      Feb 29 '12 at 8:25






                                    • 3





                                      Chrome supports console.time() and console.timeEnd() too now.

                                      – julien_c
                                      Mar 15 '12 at 11:01














                                    17












                                    17








                                    17







                                    Use Firebug, enable both Console and Javascript. Click Profile. Reload. Click Profile again. View the report.






                                    share|improve this answer













                                    Use Firebug, enable both Console and Javascript. Click Profile. Reload. Click Profile again. View the report.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 24 '08 at 11:14









                                    Stefan MaiStefan Mai

                                    17.3k64453




                                    17.3k64453








                                    • 7





                                      Good advice but obviously works only for FF. We often want to compare browser speeds... :-)

                                      – PhiLho
                                      Nov 24 '08 at 11:27






                                    • 3





                                      On new Firebuq they hide this options to menu, use CTRL + SHIFT + P or console.profile(); console..profileEnd()

                                      – user956584
                                      Feb 29 '12 at 8:25






                                    • 3





                                      Chrome supports console.time() and console.timeEnd() too now.

                                      – julien_c
                                      Mar 15 '12 at 11:01














                                    • 7





                                      Good advice but obviously works only for FF. We often want to compare browser speeds... :-)

                                      – PhiLho
                                      Nov 24 '08 at 11:27






                                    • 3





                                      On new Firebuq they hide this options to menu, use CTRL + SHIFT + P or console.profile(); console..profileEnd()

                                      – user956584
                                      Feb 29 '12 at 8:25






                                    • 3





                                      Chrome supports console.time() and console.timeEnd() too now.

                                      – julien_c
                                      Mar 15 '12 at 11:01








                                    7




                                    7





                                    Good advice but obviously works only for FF. We often want to compare browser speeds... :-)

                                    – PhiLho
                                    Nov 24 '08 at 11:27





                                    Good advice but obviously works only for FF. We often want to compare browser speeds... :-)

                                    – PhiLho
                                    Nov 24 '08 at 11:27




                                    3




                                    3





                                    On new Firebuq they hide this options to menu, use CTRL + SHIFT + P or console.profile(); console..profileEnd()

                                    – user956584
                                    Feb 29 '12 at 8:25





                                    On new Firebuq they hide this options to menu, use CTRL + SHIFT + P or console.profile(); console..profileEnd()

                                    – user956584
                                    Feb 29 '12 at 8:25




                                    3




                                    3





                                    Chrome supports console.time() and console.timeEnd() too now.

                                    – julien_c
                                    Mar 15 '12 at 11:01





                                    Chrome supports console.time() and console.timeEnd() too now.

                                    – julien_c
                                    Mar 15 '12 at 11:01











                                    10














                                    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]');
                                    };


                                    Benchmark



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

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

                                    stopwatch.stop();

                                    stopwatch.printElapsed();


                                    Output



                                    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]


                                    performance.now() is optional - just pass false into StopWatch constructor function.






                                    share|improve this answer




























                                      10














                                      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]');
                                      };


                                      Benchmark



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

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

                                      stopwatch.stop();

                                      stopwatch.printElapsed();


                                      Output



                                      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]


                                      performance.now() is optional - just pass false into StopWatch constructor function.






                                      share|improve this answer


























                                        10












                                        10








                                        10







                                        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]');
                                        };


                                        Benchmark



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

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

                                        stopwatch.stop();

                                        stopwatch.printElapsed();


                                        Output



                                        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]


                                        performance.now() is optional - just pass false into StopWatch constructor function.






                                        share|improve this answer













                                        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]');
                                        };


                                        Benchmark



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

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

                                        stopwatch.stop();

                                        stopwatch.printElapsed();


                                        Output



                                        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]


                                        performance.now() is optional - just pass false into StopWatch constructor function.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Aug 8 '13 at 18:54









                                        kayz1kayz1

                                        5,72523848




                                        5,72523848























                                            10














                                            process.hrtime() is available within Node.js - it returns a value in nanoseconds



                                            var hrTime = process.hrtime()
                                            console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)





                                            share|improve this answer


























                                            • if you rather convert it to ms e-3 rather than the suggested microsecond e-6: hrtime[0] * 1000 + hrtime[1] / 1000000 -> yeah, I rather use var hrtime as well! :P

                                              – cregox
                                              Mar 25 '17 at 14:21
















                                            10














                                            process.hrtime() is available within Node.js - it returns a value in nanoseconds



                                            var hrTime = process.hrtime()
                                            console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)





                                            share|improve this answer


























                                            • if you rather convert it to ms e-3 rather than the suggested microsecond e-6: hrtime[0] * 1000 + hrtime[1] / 1000000 -> yeah, I rather use var hrtime as well! :P

                                              – cregox
                                              Mar 25 '17 at 14:21














                                            10












                                            10








                                            10







                                            process.hrtime() is available within Node.js - it returns a value in nanoseconds



                                            var hrTime = process.hrtime()
                                            console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)





                                            share|improve this answer















                                            process.hrtime() is available within Node.js - it returns a value in nanoseconds



                                            var hrTime = process.hrtime()
                                            console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Sep 29 '16 at 7:58









                                            Pang

                                            6,9001664102




                                            6,9001664102










                                            answered Mar 11 '15 at 9:49









                                            Achim KoellnerAchim Koellner

                                            520918




                                            520918













                                            • if you rather convert it to ms e-3 rather than the suggested microsecond e-6: hrtime[0] * 1000 + hrtime[1] / 1000000 -> yeah, I rather use var hrtime as well! :P

                                              – cregox
                                              Mar 25 '17 at 14:21



















                                            • if you rather convert it to ms e-3 rather than the suggested microsecond e-6: hrtime[0] * 1000 + hrtime[1] / 1000000 -> yeah, I rather use var hrtime as well! :P

                                              – cregox
                                              Mar 25 '17 at 14:21

















                                            if you rather convert it to ms e-3 rather than the suggested microsecond e-6: hrtime[0] * 1000 + hrtime[1] / 1000000 -> yeah, I rather use var hrtime as well! :P

                                            – cregox
                                            Mar 25 '17 at 14:21





                                            if you rather convert it to ms e-3 rather than the suggested microsecond e-6: hrtime[0] * 1000 + hrtime[1] / 1000000 -> yeah, I rather use var hrtime as well! :P

                                            – cregox
                                            Mar 25 '17 at 14:21











                                            7














                                            To extend vsync's code further to have the ability to return the timeEnd as a value in NodeJS use this little piece of code.



                                            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;
                                            };


                                            Now use the code like so:



                                            console.time('someFunction timer');

                                            someFunction();

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



                                            This gives you more possibilities. You can store the execution time to be used for more purposes like using it in equations, or stored in a database, sent to a remote client over websockets, served on a webpage, etc.






                                            share|improve this answer




























                                              7














                                              To extend vsync's code further to have the ability to return the timeEnd as a value in NodeJS use this little piece of code.



                                              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;
                                              };


                                              Now use the code like so:



                                              console.time('someFunction timer');

                                              someFunction();

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



                                              This gives you more possibilities. You can store the execution time to be used for more purposes like using it in equations, or stored in a database, sent to a remote client over websockets, served on a webpage, etc.






                                              share|improve this answer


























                                                7












                                                7








                                                7







                                                To extend vsync's code further to have the ability to return the timeEnd as a value in NodeJS use this little piece of code.



                                                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;
                                                };


                                                Now use the code like so:



                                                console.time('someFunction timer');

                                                someFunction();

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



                                                This gives you more possibilities. You can store the execution time to be used for more purposes like using it in equations, or stored in a database, sent to a remote client over websockets, served on a webpage, etc.






                                                share|improve this answer













                                                To extend vsync's code further to have the ability to return the timeEnd as a value in NodeJS use this little piece of code.



                                                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;
                                                };


                                                Now use the code like so:



                                                console.time('someFunction timer');

                                                someFunction();

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



                                                This gives you more possibilities. You can store the execution time to be used for more purposes like using it in equations, or stored in a database, sent to a remote client over websockets, served on a webpage, etc.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Aug 4 '13 at 4:23









                                                Levi RobertsLevi Roberts

                                                77521435




                                                77521435























                                                    5














                                                    you can use add operator also here



                                                     var start = +new Date();
                                                    callYourFunctionHere();
                                                    var end = +new Date();
                                                    var time = end - start;
                                                    console.log('total execution time = '+ time + 'ms');





                                                    share|improve this answer






























                                                      5














                                                      you can use add operator also here



                                                       var start = +new Date();
                                                      callYourFunctionHere();
                                                      var end = +new Date();
                                                      var time = end - start;
                                                      console.log('total execution time = '+ time + 'ms');





                                                      share|improve this answer




























                                                        5












                                                        5








                                                        5







                                                        you can use add operator also here



                                                         var start = +new Date();
                                                        callYourFunctionHere();
                                                        var end = +new Date();
                                                        var time = end - start;
                                                        console.log('total execution time = '+ time + 'ms');





                                                        share|improve this answer















                                                        you can use add operator also here



                                                         var start = +new Date();
                                                        callYourFunctionHere();
                                                        var end = +new Date();
                                                        var time = end - start;
                                                        console.log('total execution time = '+ time + 'ms');






                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Nov 13 '18 at 18:53

























                                                        answered Jul 2 '18 at 11:56









                                                        Alok DeshwalAlok Deshwal

                                                        474314




                                                        474314























                                                            4














                                                            Since console.time and performance.now aren't supported in some major browsers (i.e. IE10), I created a slim utility that utilizes the best available methods. However, it lacks error handling for false usages (calling End() on a not initialized timer).



                                                            Use it and improve it as you want.



                                                            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);
                                                            }
                                                            }
                                                            }





                                                            share|improve this answer






























                                                              4














                                                              Since console.time and performance.now aren't supported in some major browsers (i.e. IE10), I created a slim utility that utilizes the best available methods. However, it lacks error handling for false usages (calling End() on a not initialized timer).



                                                              Use it and improve it as you want.



                                                              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);
                                                              }
                                                              }
                                                              }





                                                              share|improve this answer




























                                                                4












                                                                4








                                                                4







                                                                Since console.time and performance.now aren't supported in some major browsers (i.e. IE10), I created a slim utility that utilizes the best available methods. However, it lacks error handling for false usages (calling End() on a not initialized timer).



                                                                Use it and improve it as you want.



                                                                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);
                                                                }
                                                                }
                                                                }





                                                                share|improve this answer















                                                                Since console.time and performance.now aren't supported in some major browsers (i.e. IE10), I created a slim utility that utilizes the best available methods. However, it lacks error handling for false usages (calling End() on a not initialized timer).



                                                                Use it and improve it as you want.



                                                                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);
                                                                }
                                                                }
                                                                }






                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Oct 17 '17 at 7:59









                                                                Karthikeyan

                                                                892511




                                                                892511










                                                                answered Sep 18 '14 at 11:14









                                                                Mx.Mx.

                                                                2,20511630




                                                                2,20511630























                                                                    4














                                                                    It may help you.



                                                                    var t0 = date.now();
                                                                    doSomething();
                                                                    var t1 = date.now();
                                                                    console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")






                                                                    share|improve this answer



















                                                                    • 1





                                                                      While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!

                                                                      – Filnor
                                                                      Mar 16 '18 at 7:09
















                                                                    4














                                                                    It may help you.



                                                                    var t0 = date.now();
                                                                    doSomething();
                                                                    var t1 = date.now();
                                                                    console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")






                                                                    share|improve this answer



















                                                                    • 1





                                                                      While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!

                                                                      – Filnor
                                                                      Mar 16 '18 at 7:09














                                                                    4












                                                                    4








                                                                    4







                                                                    It may help you.



                                                                    var t0 = date.now();
                                                                    doSomething();
                                                                    var t1 = date.now();
                                                                    console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")






                                                                    share|improve this answer













                                                                    It may help you.



                                                                    var t0 = date.now();
                                                                    doSomething();
                                                                    var t1 = date.now();
                                                                    console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")







                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Mar 16 '18 at 7:00









                                                                    Wajeeh AslamWajeeh Aslam

                                                                    412




                                                                    412








                                                                    • 1





                                                                      While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!

                                                                      – Filnor
                                                                      Mar 16 '18 at 7:09














                                                                    • 1





                                                                      While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!

                                                                      – Filnor
                                                                      Mar 16 '18 at 7:09








                                                                    1




                                                                    1





                                                                    While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!

                                                                    – Filnor
                                                                    Mar 16 '18 at 7:09





                                                                    While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!

                                                                    – Filnor
                                                                    Mar 16 '18 at 7:09











                                                                    3














                                                                    Thanks, Achim Koellner, will expand your answer a bit:



                                                                    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


                                                                    Please, note, that you shouldn't do anything apart from what you want to measure (for example, console.log will also take time to execute and will affect performance tests).



                                                                    Note, that in order by measure asynchronous functions execution time, you should insert var timeInMilliseconds = process.hrtime(t0)[1]/1000000; inside the callback. For example,



                                                                    var t0 = process.hrtime();
                                                                    someAsyncFunction(function(err, results) {
                                                                    var timeInMilliseconds = process.hrtime(t0)[1]/1000000;

                                                                    });





                                                                    share|improve this answer




























                                                                      3














                                                                      Thanks, Achim Koellner, will expand your answer a bit:



                                                                      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


                                                                      Please, note, that you shouldn't do anything apart from what you want to measure (for example, console.log will also take time to execute and will affect performance tests).



                                                                      Note, that in order by measure asynchronous functions execution time, you should insert var timeInMilliseconds = process.hrtime(t0)[1]/1000000; inside the callback. For example,



                                                                      var t0 = process.hrtime();
                                                                      someAsyncFunction(function(err, results) {
                                                                      var timeInMilliseconds = process.hrtime(t0)[1]/1000000;

                                                                      });





                                                                      share|improve this answer


























                                                                        3












                                                                        3








                                                                        3







                                                                        Thanks, Achim Koellner, will expand your answer a bit:



                                                                        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


                                                                        Please, note, that you shouldn't do anything apart from what you want to measure (for example, console.log will also take time to execute and will affect performance tests).



                                                                        Note, that in order by measure asynchronous functions execution time, you should insert var timeInMilliseconds = process.hrtime(t0)[1]/1000000; inside the callback. For example,



                                                                        var t0 = process.hrtime();
                                                                        someAsyncFunction(function(err, results) {
                                                                        var timeInMilliseconds = process.hrtime(t0)[1]/1000000;

                                                                        });





                                                                        share|improve this answer













                                                                        Thanks, Achim Koellner, will expand your answer a bit:



                                                                        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


                                                                        Please, note, that you shouldn't do anything apart from what you want to measure (for example, console.log will also take time to execute and will affect performance tests).



                                                                        Note, that in order by measure asynchronous functions execution time, you should insert var timeInMilliseconds = process.hrtime(t0)[1]/1000000; inside the callback. For example,



                                                                        var t0 = process.hrtime();
                                                                        someAsyncFunction(function(err, results) {
                                                                        var timeInMilliseconds = process.hrtime(t0)[1]/1000000;

                                                                        });






                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Dec 18 '15 at 15:29









                                                                        Andrew MarinAndrew Marin

                                                                        465613




                                                                        465613























                                                                            1














                                                                            A couple months ago I put together my own routine that times a function using Date.now() -- even though at the time the accepted method seemed to be performance.now() --
                                                                            because the performance object is not yet available (built-in) in the stable Node.js release.



                                                                            Today I was doing some more research and found another method for timing. Since I also found how to use this in Node.js code, I thought I would share it here.



                                                                            The following is combined from the examples given by w3c and Node.js:



                                                                            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)
                                                                            }


                                                                            NOTE:



                                                                            If you intend to use the performance object in a Node.js app, you must include the following require:

                                                                            const { performance } = require('perf_hooks')






                                                                            share|improve this answer






























                                                                              1














                                                                              A couple months ago I put together my own routine that times a function using Date.now() -- even though at the time the accepted method seemed to be performance.now() --
                                                                              because the performance object is not yet available (built-in) in the stable Node.js release.



                                                                              Today I was doing some more research and found another method for timing. Since I also found how to use this in Node.js code, I thought I would share it here.



                                                                              The following is combined from the examples given by w3c and Node.js:



                                                                              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)
                                                                              }


                                                                              NOTE:



                                                                              If you intend to use the performance object in a Node.js app, you must include the following require:

                                                                              const { performance } = require('perf_hooks')






                                                                              share|improve this answer




























                                                                                1












                                                                                1








                                                                                1







                                                                                A couple months ago I put together my own routine that times a function using Date.now() -- even though at the time the accepted method seemed to be performance.now() --
                                                                                because the performance object is not yet available (built-in) in the stable Node.js release.



                                                                                Today I was doing some more research and found another method for timing. Since I also found how to use this in Node.js code, I thought I would share it here.



                                                                                The following is combined from the examples given by w3c and Node.js:



                                                                                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)
                                                                                }


                                                                                NOTE:



                                                                                If you intend to use the performance object in a Node.js app, you must include the following require:

                                                                                const { performance } = require('perf_hooks')






                                                                                share|improve this answer















                                                                                A couple months ago I put together my own routine that times a function using Date.now() -- even though at the time the accepted method seemed to be performance.now() --
                                                                                because the performance object is not yet available (built-in) in the stable Node.js release.



                                                                                Today I was doing some more research and found another method for timing. Since I also found how to use this in Node.js code, I thought I would share it here.



                                                                                The following is combined from the examples given by w3c and Node.js:



                                                                                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)
                                                                                }


                                                                                NOTE:



                                                                                If you intend to use the performance object in a Node.js app, you must include the following require:

                                                                                const { performance } = require('perf_hooks')







                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                edited Mar 24 '18 at 20:15

























                                                                                answered Mar 18 '18 at 13:45









                                                                                Jonathan ChasteenJonathan Chasteen

                                                                                114




                                                                                114























                                                                                    1














                                                                                    Here's a decorator for timing functions



                                                                                    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;
                                                                                    }


                                                                                    Usage:



                                                                                    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'


                                                                                    If you're using async functions you can make timed async and add an await before f(...args), and that should work for those. It gets more complicated if you want one decorator to handle both sync and async functions.






                                                                                    share|improve this answer




























                                                                                      1














                                                                                      Here's a decorator for timing functions



                                                                                      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;
                                                                                      }


                                                                                      Usage:



                                                                                      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'


                                                                                      If you're using async functions you can make timed async and add an await before f(...args), and that should work for those. It gets more complicated if you want one decorator to handle both sync and async functions.






                                                                                      share|improve this answer


























                                                                                        1












                                                                                        1








                                                                                        1







                                                                                        Here's a decorator for timing functions



                                                                                        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;
                                                                                        }


                                                                                        Usage:



                                                                                        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'


                                                                                        If you're using async functions you can make timed async and add an await before f(...args), and that should work for those. It gets more complicated if you want one decorator to handle both sync and async functions.






                                                                                        share|improve this answer













                                                                                        Here's a decorator for timing functions



                                                                                        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;
                                                                                        }


                                                                                        Usage:



                                                                                        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'


                                                                                        If you're using async functions you can make timed async and add an await before f(...args), and that should work for those. It gets more complicated if you want one decorator to handle both sync and async functions.







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Sep 12 '18 at 1:41









                                                                                        aljgomaljgom

                                                                                        1,2361012




                                                                                        1,2361012























                                                                                            0














                                                                                            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;
                                                                                            }
                                                                                            }
                                                                                            }


                                                                                            InitTime related to string.



                                                                                            return Singleton.getInstance().initTime(label); // Returns the time init



                                                                                            return Singleton.getInstance().endTime(label); // Returns the total time between init and end






                                                                                            share|improve this answer




























                                                                                              0














                                                                                              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;
                                                                                              }
                                                                                              }
                                                                                              }


                                                                                              InitTime related to string.



                                                                                              return Singleton.getInstance().initTime(label); // Returns the time init



                                                                                              return Singleton.getInstance().endTime(label); // Returns the total time between init and end






                                                                                              share|improve this answer


























                                                                                                0












                                                                                                0








                                                                                                0







                                                                                                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;
                                                                                                }
                                                                                                }
                                                                                                }


                                                                                                InitTime related to string.



                                                                                                return Singleton.getInstance().initTime(label); // Returns the time init



                                                                                                return Singleton.getInstance().endTime(label); // Returns the total time between init and end






                                                                                                share|improve this answer













                                                                                                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;
                                                                                                }
                                                                                                }
                                                                                                }


                                                                                                InitTime related to string.



                                                                                                return Singleton.getInstance().initTime(label); // Returns the time init



                                                                                                return Singleton.getInstance().endTime(label); // Returns the total time between init and end







                                                                                                share|improve this answer












                                                                                                share|improve this answer



                                                                                                share|improve this answer










                                                                                                answered Aug 14 '18 at 13:38









                                                                                                jose920405jose920405

                                                                                                5,74823050




                                                                                                5,74823050























                                                                                                    0














                                                                                                    If you want to measure the time between multiple things that aren't nested you could use this:



                                                                                                    function timer(lap){ 
                                                                                                    if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
                                                                                                    timer.prev = performance.now();
                                                                                                    }


                                                                                                    Similar to console.time(), but easier usage if you don't need to keep track of previous timers.



                                                                                                    If you like the blue color from console.time(), you can use this line instead



                                                                                                    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'





                                                                                                    share|improve this answer






























                                                                                                      0














                                                                                                      If you want to measure the time between multiple things that aren't nested you could use this:



                                                                                                      function timer(lap){ 
                                                                                                      if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
                                                                                                      timer.prev = performance.now();
                                                                                                      }


                                                                                                      Similar to console.time(), but easier usage if you don't need to keep track of previous timers.



                                                                                                      If you like the blue color from console.time(), you can use this line instead



                                                                                                      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'





                                                                                                      share|improve this answer




























                                                                                                        0












                                                                                                        0








                                                                                                        0







                                                                                                        If you want to measure the time between multiple things that aren't nested you could use this:



                                                                                                        function timer(lap){ 
                                                                                                        if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
                                                                                                        timer.prev = performance.now();
                                                                                                        }


                                                                                                        Similar to console.time(), but easier usage if you don't need to keep track of previous timers.



                                                                                                        If you like the blue color from console.time(), you can use this line instead



                                                                                                        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'





                                                                                                        share|improve this answer















                                                                                                        If you want to measure the time between multiple things that aren't nested you could use this:



                                                                                                        function timer(lap){ 
                                                                                                        if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
                                                                                                        timer.prev = performance.now();
                                                                                                        }


                                                                                                        Similar to console.time(), but easier usage if you don't need to keep track of previous timers.



                                                                                                        If you like the blue color from console.time(), you can use this line instead



                                                                                                        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'






                                                                                                        share|improve this answer














                                                                                                        share|improve this answer



                                                                                                        share|improve this answer








                                                                                                        edited Sep 11 '18 at 22:52

























                                                                                                        answered Apr 3 '17 at 11:11









                                                                                                        aljgomaljgom

                                                                                                        1,2361012




                                                                                                        1,2361012























                                                                                                            0














                                                                                                            In my case, I perfer to use @ grammar suger and compile it with babel.

                                                                                                            The problem of this method is that function has to be inside object.



                                                                                                            Sample JS Code



                                                                                                            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)


                                                                                                            .babelrc (for babel 6)



                                                                                                             {
                                                                                                            "plugins": [
                                                                                                            "transform-decorators-legacy"
                                                                                                            ]
                                                                                                            }





                                                                                                            share|improve this answer






























                                                                                                              0














                                                                                                              In my case, I perfer to use @ grammar suger and compile it with babel.

                                                                                                              The problem of this method is that function has to be inside object.



                                                                                                              Sample JS Code



                                                                                                              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)


                                                                                                              .babelrc (for babel 6)



                                                                                                               {
                                                                                                              "plugins": [
                                                                                                              "transform-decorators-legacy"
                                                                                                              ]
                                                                                                              }





                                                                                                              share|improve this answer




























                                                                                                                0












                                                                                                                0








                                                                                                                0







                                                                                                                In my case, I perfer to use @ grammar suger and compile it with babel.

                                                                                                                The problem of this method is that function has to be inside object.



                                                                                                                Sample JS Code



                                                                                                                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)


                                                                                                                .babelrc (for babel 6)



                                                                                                                 {
                                                                                                                "plugins": [
                                                                                                                "transform-decorators-legacy"
                                                                                                                ]
                                                                                                                }





                                                                                                                share|improve this answer















                                                                                                                In my case, I perfer to use @ grammar suger and compile it with babel.

                                                                                                                The problem of this method is that function has to be inside object.



                                                                                                                Sample JS Code



                                                                                                                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)


                                                                                                                .babelrc (for babel 6)



                                                                                                                 {
                                                                                                                "plugins": [
                                                                                                                "transform-decorators-legacy"
                                                                                                                ]
                                                                                                                }






                                                                                                                share|improve this answer














                                                                                                                share|improve this answer



                                                                                                                share|improve this answer








                                                                                                                edited Sep 29 '18 at 20:34

























                                                                                                                answered Sep 29 '18 at 19:45









                                                                                                                Yu HuangYu Huang

                                                                                                                752814




                                                                                                                752814























                                                                                                                    -1














                                                                                                                    Stopwatch with cumulative cycles



                                                                                                                    Works with server and client (Node or DOM), uses the Performance API.
                                                                                                                    Good when you have many small cycles e.g. in a function called 1000 times that processes 1000 data objects but you want to see how each operation in this function adds up to the total.



                                                                                                                    So this one uses a module global (singleton) timer. Same as a class singleton pattern, just a bit simpler to use, but you need to put this in a separate e.g. stopwatch.js file.



                                                                                                                    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];
                                                                                                                    }
                                                                                                                    };





                                                                                                                    share|improve this answer




























                                                                                                                      -1














                                                                                                                      Stopwatch with cumulative cycles



                                                                                                                      Works with server and client (Node or DOM), uses the Performance API.
                                                                                                                      Good when you have many small cycles e.g. in a function called 1000 times that processes 1000 data objects but you want to see how each operation in this function adds up to the total.



                                                                                                                      So this one uses a module global (singleton) timer. Same as a class singleton pattern, just a bit simpler to use, but you need to put this in a separate e.g. stopwatch.js file.



                                                                                                                      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];
                                                                                                                      }
                                                                                                                      };





                                                                                                                      share|improve this answer


























                                                                                                                        -1












                                                                                                                        -1








                                                                                                                        -1







                                                                                                                        Stopwatch with cumulative cycles



                                                                                                                        Works with server and client (Node or DOM), uses the Performance API.
                                                                                                                        Good when you have many small cycles e.g. in a function called 1000 times that processes 1000 data objects but you want to see how each operation in this function adds up to the total.



                                                                                                                        So this one uses a module global (singleton) timer. Same as a class singleton pattern, just a bit simpler to use, but you need to put this in a separate e.g. stopwatch.js file.



                                                                                                                        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];
                                                                                                                        }
                                                                                                                        };





                                                                                                                        share|improve this answer













                                                                                                                        Stopwatch with cumulative cycles



                                                                                                                        Works with server and client (Node or DOM), uses the Performance API.
                                                                                                                        Good when you have many small cycles e.g. in a function called 1000 times that processes 1000 data objects but you want to see how each operation in this function adds up to the total.



                                                                                                                        So this one uses a module global (singleton) timer. Same as a class singleton pattern, just a bit simpler to use, but you need to put this in a separate e.g. stopwatch.js file.



                                                                                                                        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];
                                                                                                                        }
                                                                                                                        };






                                                                                                                        share|improve this answer












                                                                                                                        share|improve this answer



                                                                                                                        share|improve this answer










                                                                                                                        answered 2 days ago









                                                                                                                        gombosggombosg

                                                                                                                        912




                                                                                                                        912























                                                                                                                            -2














                                                                                                                            As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:



                                                                                                                            //=-=|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}}}();


                                                                                                                            Compilation was a success!




                                                                                                                            • Original Size: 219 bytes gzipped (405 bytes uncompressed)

                                                                                                                            • Compiled Size: 109 bytes gzipped (187 bytes uncompressed)

                                                                                                                            • Saved 50.23% off the gzipped size (53.83% without gzip






                                                                                                                            share|improve this answer




























                                                                                                                              -2














                                                                                                                              As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:



                                                                                                                              //=-=|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}}}();


                                                                                                                              Compilation was a success!




                                                                                                                              • Original Size: 219 bytes gzipped (405 bytes uncompressed)

                                                                                                                              • Compiled Size: 109 bytes gzipped (187 bytes uncompressed)

                                                                                                                              • Saved 50.23% off the gzipped size (53.83% without gzip






                                                                                                                              share|improve this answer


























                                                                                                                                -2












                                                                                                                                -2








                                                                                                                                -2







                                                                                                                                As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:



                                                                                                                                //=-=|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}}}();


                                                                                                                                Compilation was a success!




                                                                                                                                • Original Size: 219 bytes gzipped (405 bytes uncompressed)

                                                                                                                                • Compiled Size: 109 bytes gzipped (187 bytes uncompressed)

                                                                                                                                • Saved 50.23% off the gzipped size (53.83% without gzip






                                                                                                                                share|improve this answer













                                                                                                                                As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:



                                                                                                                                //=-=|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}}}();


                                                                                                                                Compilation was a success!




                                                                                                                                • Original Size: 219 bytes gzipped (405 bytes uncompressed)

                                                                                                                                • Compiled Size: 109 bytes gzipped (187 bytes uncompressed)

                                                                                                                                • Saved 50.23% off the gzipped size (53.83% without gzip







                                                                                                                                share|improve this answer












                                                                                                                                share|improve this answer



                                                                                                                                share|improve this answer










                                                                                                                                answered Mar 16 '14 at 21:21









                                                                                                                                NlaakALDNlaakALD

                                                                                                                                1321212




                                                                                                                                1321212























                                                                                                                                    -5














                                                                                                                                    The accepted answer is wrong !



                                                                                                                                    Since JavaScript is asynchronous, the values of the variable end of the accepted answer would be wrong.



                                                                                                                                    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);


                                                                                                                                    The execution of the for may be very fast so you can not see that the result is wrong. You can test it with a code doing some request :



                                                                                                                                    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);


                                                                                                                                    So the alert will prompt very quickly but in the console you'll see that the ajax requests are continuing.



                                                                                                                                    Here is how you should do it : https://developer.mozilla.org/en-US/docs/Web/API/Performance.now






                                                                                                                                    share|improve this answer



















                                                                                                                                    • 7





                                                                                                                                      It's not because of the for loop. A for loop will wait until the last loop until it will go on down your sourcecode. AJAX calls are async. And there are also other functions that run async. But a for loop is not executet async.

                                                                                                                                      – Scriptlabs
                                                                                                                                      Mar 12 '15 at 19:21


















                                                                                                                                    -5














                                                                                                                                    The accepted answer is wrong !



                                                                                                                                    Since JavaScript is asynchronous, the values of the variable end of the accepted answer would be wrong.



                                                                                                                                    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);


                                                                                                                                    The execution of the for may be very fast so you can not see that the result is wrong. You can test it with a code doing some request :



                                                                                                                                    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);


                                                                                                                                    So the alert will prompt very quickly but in the console you'll see that the ajax requests are continuing.



                                                                                                                                    Here is how you should do it : https://developer.mozilla.org/en-US/docs/Web/API/Performance.now






                                                                                                                                    share|improve this answer



















                                                                                                                                    • 7





                                                                                                                                      It's not because of the for loop. A for loop will wait until the last loop until it will go on down your sourcecode. AJAX calls are async. And there are also other functions that run async. But a for loop is not executet async.

                                                                                                                                      – Scriptlabs
                                                                                                                                      Mar 12 '15 at 19:21
















                                                                                                                                    -5












                                                                                                                                    -5








                                                                                                                                    -5







                                                                                                                                    The accepted answer is wrong !



                                                                                                                                    Since JavaScript is asynchronous, the values of the variable end of the accepted answer would be wrong.



                                                                                                                                    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);


                                                                                                                                    The execution of the for may be very fast so you can not see that the result is wrong. You can test it with a code doing some request :



                                                                                                                                    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);


                                                                                                                                    So the alert will prompt very quickly but in the console you'll see that the ajax requests are continuing.



                                                                                                                                    Here is how you should do it : https://developer.mozilla.org/en-US/docs/Web/API/Performance.now






                                                                                                                                    share|improve this answer













                                                                                                                                    The accepted answer is wrong !



                                                                                                                                    Since JavaScript is asynchronous, the values of the variable end of the accepted answer would be wrong.



                                                                                                                                    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);


                                                                                                                                    The execution of the for may be very fast so you can not see that the result is wrong. You can test it with a code doing some request :



                                                                                                                                    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);


                                                                                                                                    So the alert will prompt very quickly but in the console you'll see that the ajax requests are continuing.



                                                                                                                                    Here is how you should do it : https://developer.mozilla.org/en-US/docs/Web/API/Performance.now







                                                                                                                                    share|improve this answer












                                                                                                                                    share|improve this answer



                                                                                                                                    share|improve this answer










                                                                                                                                    answered Feb 3 '15 at 16:02









                                                                                                                                    Mirza SelimovicMirza Selimovic

                                                                                                                                    1,0571018




                                                                                                                                    1,0571018








                                                                                                                                    • 7





                                                                                                                                      It's not because of the for loop. A for loop will wait until the last loop until it will go on down your sourcecode. AJAX calls are async. And there are also other functions that run async. But a for loop is not executet async.

                                                                                                                                      – Scriptlabs
                                                                                                                                      Mar 12 '15 at 19:21
















                                                                                                                                    • 7





                                                                                                                                      It's not because of the for loop. A for loop will wait until the last loop until it will go on down your sourcecode. AJAX calls are async. And there are also other functions that run async. But a for loop is not executet async.

                                                                                                                                      – Scriptlabs
                                                                                                                                      Mar 12 '15 at 19:21










                                                                                                                                    7




                                                                                                                                    7





                                                                                                                                    It's not because of the for loop. A for loop will wait until the last loop until it will go on down your sourcecode. AJAX calls are async. And there are also other functions that run async. But a for loop is not executet async.

                                                                                                                                    – Scriptlabs
                                                                                                                                    Mar 12 '15 at 19:21







                                                                                                                                    It's not because of the for loop. A for loop will wait until the last loop until it will go on down your sourcecode. AJAX calls are async. And there are also other functions that run async. But a for loop is not executet async.

                                                                                                                                    – Scriptlabs
                                                                                                                                    Mar 12 '15 at 19:21




















                                                                                                                                    draft saved

                                                                                                                                    draft discarded




















































                                                                                                                                    Thanks for contributing an answer to Stack Overflow!


                                                                                                                                    • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                    But avoid



                                                                                                                                    • Asking for help, clarification, or responding to other answers.

                                                                                                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                    To learn more, see our tips on writing great answers.




                                                                                                                                    draft saved


                                                                                                                                    draft discarded














                                                                                                                                    StackExchange.ready(
                                                                                                                                    function () {
                                                                                                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f313893%2fhow-to-measure-time-taken-by-a-function-to-execute%23new-answer', 'question_page');
                                                                                                                                    }
                                                                                                                                    );

                                                                                                                                    Post as a guest















                                                                                                                                    Required, but never shown





















































                                                                                                                                    Required, but never shown














                                                                                                                                    Required, but never shown












                                                                                                                                    Required, but never shown







                                                                                                                                    Required, but never shown

































                                                                                                                                    Required, but never shown














                                                                                                                                    Required, but never shown












                                                                                                                                    Required, but never shown







                                                                                                                                    Required, but never shown







                                                                                                                                    Popular posts from this blog

                                                                                                                                    Florida Star v. B. J. F.

                                                                                                                                    Error while running script in elastic search , gateway timeout

                                                                                                                                    Adding quotations to stringified JSON object values