Benchmarking your code - measuring execution time

suggest change

Most performance tips depend on the current state of JavaScript engines and stay relevant only for a while. The fundamental law of performance optimization is that you must first measure before trying to optimize, and measure again after a presumed optimization.

To measure code execution time, you can use different time measurement tools like:

The Performance interface exposes timing information for the page. Modern Node.js also provides a global performance object. The performance.now() examples below are about that clock, not Node’s process.hrtime.

process.hrtime on Node.js gives you timing information as [seconds, nanoseconds] tuples. Called without argument it returns an arbitrary time but called with a previously returned value as argument it returns the difference between the two executions.

Console timers console.time("labelName") starts a timer you can use to track how long an operation takes. You give each timer a unique label name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd("labelName") with the same name, the browser will finish the timer for given name and output the time in milliseconds, that elapsed since the timer was started. The strings passed to time() and timeEnd() must match otherwise the timer will not finish.

Date.now function Date.now() returns current Timestamp in milliseconds, which is a Number representation of time since 1 January 1970 00:00:00 UTC until now. The method now() is a static method of Date, therefore you always use it as Date.now().

Example 1 using: performance.now()

In this example we are going to calculate the elapsed time for the execution of our function, and we are going to use the Performance.now() method that returns a DOMHighResTimeStamp, measured in milliseconds, accurate to one thousandth of a millisecond.

let startTime; let endTime;

function myFunction() {
    //Slow code you want to measure
}

//Get the start time
startTime = performance.now();

//Call the time-consuming function
myFunction();

//Get the end time
endTime = performance.now();

//The difference is how many milliseconds it took to call myFunction()
console.debug('Elapsed time:', (endTime - startTime));

The result in console will look something like this:

Elapsed time: 0.10000000009313226

Usage of performance.now() has the highest precision in browsers with accuracy to one thousandth of a millisecond, but the lowest compatibility.

Example 2 using: Date.now()

In this example we are going to calculate the elapsed time for the initialization of a big array (1 million values), and we are going to use the Date.now() method

const t0 = Date.now(); //stores current Timestamp in milliseconds since 1 January 1970 00:00:00 UTC
const arr = []; //store empty array
for (let i = 0; i < 1000000; i++) { //1 million iterations
   arr.push(i); //push current i value
}
console.log(Date.now() - t0); //print elapsed time between stored t0 and now

Example 3 using: console.time("label") & console.timeEnd("label")

In this example we are doing the same task as in Example 2, but we are going to use the console.time("label") & console.timeEnd("label") methods

console.time("t"); //start new timer for label name: "t"
const arr = []; //store empty array
for(let i = 0; i < 1000000; i++) { //1 million iterations
   arr.push(i); //push current i value
}
console.timeEnd("t"); //stop the timer for label name: "t" and print elapsed time

Example 4 using process.hrtime()

In Node.js programs this is the most precise way to measure spent time.

const start = process.hrtime();

// long execution here, maybe asynchronous

const diff = process.hrtime(start);
// returns for example [ 1, 2325 ]
console.log(`Operation took ${diff[0] * 1e9 + diff[1]} nanoseconds`);
// logs: Operation took 1000002325 nanoseconds

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents