Learn different ways to measure the time it takes to execute programs in JavaScript

To find how much time a function, loop, or any operation takes to execute in JavaScript, we can use one of the following tools:
- Using
console.timeandconsole.timeEnd - Using the
performance.nowmethod - Using online performance testing tools
1. Using console.time and console.timeEnd
The console.time and console.timeEnd will print the number of millisecond taken to execute the code between the function calls.
function test() {
for(let i =0 ; i < 100000; i++) {
//operation;
}
}
console.time();
test();
console.timeEnd();
// This will produce
default: 1.2529296875ms (time taken to execute test function, value may vary ).
We can also use labels to tag different timing operations.
console.time("test");
test();
console.timeEnd("test");
// test: 1.117919921875ms
We can use nested console.time with different label
console.time("test1");
test();
console.time("test2");
test();
console.timeEnd("test2");
console.timeEnd("test1");
test2: 0.875ms
test1: 2.1748046875ms
You can write a method which will automatically handle Logging perfomance
function runTest(fn, n = 1){
console.time("Test");
for(let i =0 ; i < n; i++) {
fn();
}
console.timeEnd("Test");
}
// we can pass the function and number of iteration .
For comparing two functions
function compareFunction(fn1, fn2, n = 1) {
console.time("Fn1");
for(let i =0 ; i < n; i++) {
fn1();
}
console.timeEnd("Fn1");
console.time("Fn2");
for(let i =0 ; i < n; i++) {
fn2();
}
console.timeEnd("Fn2");
}
// we can pass the function and number of iteration .
2. Using performance.now()
The performance.now() method will return a timestamp in milliseconds of how long it’s been since you loaded the page.
Let’s try to print the value once the window is loaded.
window.onload = function (ev) {
console.log(performance.now()); // the value will be around 100ms
}
Let’s use that to check the performance:
var start = performance.now();
test();
var end = performance.now();
var timeTaken = end - start; // 1.1350000277161598
But Mozilla says
The timestamp is not actually high-resolution. To mitigate security threats such as Spectre, browsers currently round the results to varying degrees. (Firefox started rounding to 1 millisecond in Firefox 60). Some browsers may also slightly randomise the timestamp. The precision may improve again in future releases; browser developers are still investigating these timing attacks and how best to mitigate them.
Online Testing Tools
Online performance testing tools will execute our JavaScript code, run benchmarks, and give us the performance result. Three of the best online testing tools are:
Join your hand 🤚 with me JavaScript Jeep🚙💨 .
