Last Updated: February 25, 2016
·
13.32K
· avnerner

How to measure your Javascript to the nanosecond level?

All major browsers and Node supports a very easy logging method to measure execution time of your Javascript for easy profiling.

Say you have a long running loop:

var arr = [] , loopCount = 5000;
    for (var i=0 ; i <loopCount; i++){
        arr.push(Math.random() * 50000);
    }

To measure the overall execution time simply wrap with console.time() and console.timeEnd() :

var title= "Loop on numbers"
console.time(title);
var arr = [] , loopCount = 5000;
    for (var i=0 ; i <loopCount; i++){
        arr.push(Math.random() * 50000);
    }
console.timeEnd(title);

The execution will be printed in the console in a milliseconds accuracy.

At times, you might want to measure something to the nanosecond level.

Node.JS provides a way to do that using the High Resolution process API, here is the same loop using process.hrtime():

var title= "Loop on numberss", t = process.hrtime();
var arr = [] , loopCount = 5000;
for (var i=0 ; i <loopCount; i++){
    arr.push(Math.random() * 50000);
}
var t1 = process.hrtime(t);
console.log("%s %d seconds and %d nanoseconds", title, t1[0], t1[1]);

<Later that day> Edit :
Paul Irish posted the following timely post: http://updates.html5rocks.com/2012/08/When-milliseconds-are-not-enough-performance-now

Demonstrating the usage of:
window.performance.webkitNow()
For High resolution accuracy on the browser as well.