JavaScript: Measure the time taken by a function to execute
JavaScript fundamental (ES6 Syntax): Exercise-28 with Solution
Write a JavaScript program to measure the time a function to execute.
- Use Console.time() and Console.timeEnd() to measure the difference between the start and end times to determine how long the callback took to execute.
Sample Solution:
JavaScript Code:
const time_taken = callback => {
const result = callback();
return result;
};
console.log("Time taken: " + time_taken(() => Math.pow(2, 10))+" ms");
console.log("Time taken: " + time_taken(() => Math.sqrt(225))+" ms");
console.log("Time taken: " + time_taken(() => Math.sqrt((5 * 5) + (6 * 6)))+" ms");
Sample Output:
Time taken: 1024 ms Time taken: 15 ms Time taken: 7.810249675906654 ms
Flowchart:

Note : The code above is written in ES6 and can be executed as intended on Chrome Developer Tools.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to find every element that exists in any of the two given arrays once, using a provided comparator function.
Next: Write a JavaScript program to convert a value to a safe integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join