Tuesday, September 17, 2024

How to Calculate Code Execution Time in jQuery

 


Here are some methods to calculate code execution time in jQuery.


1. Using console.time(label), console.timeEnd(label)


function sayHello(i){

     console.log(i, 'Hello world!');

}

 

// Start the timer with label "codeTimer"

console.time("codeTimer");  


// Code being timed

for (let index = 0; index < 100; index++) {

     sayHello(index);

}


// Stop the timer and logs the elapsed time with the same label "codeTimer"

console.timeEnd("codeTimer");  


2.Using Date


//Set start point where you want

var start = new Date(); 


// Code being timed

for (let index = 0; index < 10000; index++) {

     sayHello(index);

}


//Set end point where you want

var end = new Date();


//Get the elapsed time in milliseconds

var duration = end - start;


console.log('Code execution took', duration, 'milliseconds')


3. Using performance


// Take a timestamp at the beginning before executing the code being timed

var start = performance.now();


// Code being timed

for (let index = 0; index < 10000; index++) {

     sayHello(index);

}


// Take a final timestamp to stop time measurement

var end = performance.now();



//Get the elapsed time in milliseconds

var duration = end - start;


console.log('Code execution took', duration, 'milliseconds')

No comments:

Post a Comment

Blog Posts

Enhancing Performance of Java-Web Applications

Applications built with a Java back-end, a relational database (such as Oracle or MySQL), and a JavaScript-based front-end form a common and...