In JavaScript, you can measure how long a function takes to execute by recording the time before and after the function call. This is useful for analyzing performance and identifying potential bottlenecks.
- Date can be used to calculate elapsed time in milliseconds.
- performance.now() provides a high-resolution timestamp and is preferred for performance measurements.
- console.time() and console.timeEnd() provide a simple way to measure and display execution time in the console.
- Measuring execution time can help compare and optimize different implementations.
The following approaches can be used to measure the execution time of a function in JavaScript.
Approach 1: Using the Date Object
The Date.now() method returns the current timestamp in milliseconds. By recording the timestamp before and after a function executes and subtracting the two values, we can calculate the approximate execution time.
Working:
- Get the current time before calling the function using Date.now().
- Execute the function.
- Get the current time again after the function completes.
- Subtract the start time from the end time.
<!DOCTYPE html>
<html>
<head>
<title>Measure Execution Time</title>
</head>
<body>
<h1 style="color: green">GeeksforGeeks</h1>
<b>
How to measure time taken by a function
to execute using JavaScript?
</b>
<p>
Click on the button to measure the execution time
of the function. The result will be displayed
in the console.
</p>
<button onclick="measurePerformance()">
Click to Check
</button>
<script>
function measurePerformance() {
// Get the starting time
const startTime = Date.now();
// Call the function
exampleFunction();
// Get the ending time
const endTime = Date.now();
// Calculate execution time
const timeTaken = endTime - startTime;
console.log(
"Function took " + timeTaken + " milliseconds"
);
}
function exampleFunction() {
let sum = 0;
for (let i = 0; i < 1000000; i++) {
sum += i;
}
return sum;
}
</script>
</body>
</html>
Note: The exact execution time can vary depending on the browser, system, and current workload.
Syntax:
const startTime = Date.now();
functionToCall();
const endTime = Date.now();
const executionTime = endTime - startTime;
Approach 2: Using performance.now()
The performance.now() method returns a high-resolution timestamp in milliseconds. Unlike Date.now(), it uses a monotonic clock and provides greater precision, making it suitable for measuring short-running operations.
Working:
- Get the starting timestamp using performance.now().
- Execute the function.
- Get the ending timestamp.
- Subtract the starting timestamp from the ending timestamp.
<!DOCTYPE html>
<html>
<head>
<title>Measure Execution Time</title>
</head>
<body>
<h1 style="color: green">GeeksforGeeks</h1>
<b>
How to measure time taken by a function
to execute using JavaScript?
</b>
<p>
Click on the button to measure the execution time
of the function. The result will be displayed
in the console.
</p>
<button onclick="measurePerformance()">
Click to Check
</button>
<script>
function measurePerformance() {
// Get the starting time
const start = performance.now();
// Call the function
exampleFunction();
// Get the ending time
const end = performance.now();
// Calculate execution time
const timeTaken = end - start;
console.log(
"Function took " + timeTaken + " milliseconds"
);
}
function exampleFunction() {
let sum = 0;
for (let i = 0; i < 1000000; i++) {
sum += i;
}
return sum;
}
</script>
</body>
</html>
Note: The output is only an example. The actual value may vary between executions.
Syntax:
const startTime = performance.now();
functionToCall();
const endTime = performance.now();
- performance.now() returns a high-resolution timestamp.
- The function is executed between the two timestamp calls.
- Subtracting the start time from the end time gives the elapsed time.
- This approach is generally preferred for measuring short-running code.
Approach 3: Using console.time() and console.timeEnd()
The console.time() method starts a timer with a specified label, while console.timeEnd() stops the timer with the same label and displays the elapsed time in the console.
Working:
- Call console.time() with a unique label to start the timer.
- Execute the function whose performance needs to be measured.
- Call console.timeEnd() with the same label.
- The elapsed time is automatically displayed in the console.
<!DOCTYPE html>
<html>
<head>
<title>Measure Execution Time</title>
</head>
<body>
<h1 style="color: green">GeeksforGeeks</h1>
<b>
How to measure time taken by a function
to execute using JavaScript?
</b>
<p>
Click on the button to measure the execution time
of the function. The result will be displayed
in the console.
</p>
<button onclick="measurePerformance()">
Click to Check
</button>
<script>
function measurePerformance() {
// Start the timer
console.time("functionExecution");
// Call the function
exampleFunction();
// Stop the timer
console.timeEnd("functionExecution");
}
function exampleFunction() {
let sum = 0;
for (let i = 0; i < 1000000; i++) {
sum += i;
}
return sum;
}
</script>
</body>
</html>
Syntax:
console.time("label");
functionToCall();
console.timeEnd("label");
- console.time("label") starts a timer.
- functionToCall() executes the function whose performance is being measured.
- console.timeEnd("label") stops the timer and displays the elapsed time.
- The same label must be used with both methods.