How to find the time taken to execute a function in JavaScript

Key takeaways:

  • We can compare the performance of different function implementations by measuring their execution times, enabling us to select the most efficient option.

  • We can measure the time taken to execute a function by using the following methods:

    • Date.now(): A straightforward approach that provides the time in milliseconds.

    • console.time() and console.timeEnd(): A convenient way to measure the time between two points in code execution with labeled timers.

    • performance.now(): The most precise method, offering high-resolution timestamps for accurate measurements, particularly for shorter execution times.

  • Monitoring execution time helps us evaluate the impact of code changes, ensuring that our optimizations lead to genuine performance improvements.

  • For scenarios where execution times are very short, performance.now() provides high-resolution timestamps, making it the preferred method for accurate measurements.

We often need to optimize our code to improve performance. One crucial aspect of this optimization is understanding how long our functions take to execute. By measuring execution time, we can identify bottlenecks and make informed decisions on where to focus our optimization efforts. In this Answer, we will learn how to find the time taken to execute a function in JavaScript.

Why measure execution time?

Measuring execution time helps us:

  • Identify slow-performing functions.

  • Compare the performance of different implementations.

  • Understand the impact of changes in code on performance.

  • Optimize user experience by reducing loading times.

Let’s dive into how we can measure the execution time of functions in JavaScript.

Measuring the execution time of a function

We can find the time taken to execute a function by using:

Method 1: Using the Date.now() object

We can use the Date.now() method to get the current time in milliseconds. The method helps us get the time before and after executing a function. We find the difference between the time after executing the function and the time before executing the function. This will result in the time taken to execute the function.

function test(){
for(let i = 0; i < 1000000000; i++){
continue;
}
}
// Start measuring time
let start = Date.now();
// Call the function
test();
// End measuring time
let timeTaken = Date.now() - start;
console.log("Total time taken : " + timeTaken + " milliseconds");

In the above code:

  • Lines 1–5: We create a function test() with a for loop.

  • Line 8: We get the current time in milliseconds and store it in a variable named start.

  • Line 10: We call the test() method.

  • Line 12: We calculate the time taken to execute the test() function by subtracting the current time from the start time, which we will store before executing the function.

  • Line 14: We print the time taken to execute the test() function.

Method 2: Using console.time() and console.timeEnd()

JavaScript provides a simple way to measure execution time using the console.time() and console.timeEnd() methods. These methods allow us to start and stop a timer, giving us the elapsed time between the two calls. We call the console.time() to initiate a timer with a name. We call the console.timeEnd() method to stop the timer. This is used to get the time taken to execute a function.

function test(){
for(let i = 0; i < 1000000000; i++){
continue;
}
}
// Start measuring time
console.time("Execution Time");
// Call the function
test();
// End measuring time
console.timeEnd("Execution Time");

In the above code:

  • Lines 1–5: We create a function test() with a for loop.

  • Line 8: We call the console.time() method with Execution Time as an argument. This will start the timer with Execution Time as the label.

  • Line 10: We call the test() method.

  • Line 12: We call the console.timeEnd() method for the label Execution Time. This will stop the timer and print the number of milliseconds between the call of console.time() and console.timeEnd().

Method 3: Using the performace.now() method

For more precise measurements, especially in scenarios where execution time is very short, we can use the performance.now() method. This method returns a timestamp measured in milliseconds, including fractions of a millisecond. The performance.now() method returns the time passed. This method returns the time as floating-point numbers with up to microsecond precision.

function test(){
for(let i = 0; i < 1000000000; i++){
continue;
}
}
// Start measuring time
let startTime = performance.now();
// Call the function
test();
// End measuring time
let endTime = performance.now();
let timeTaken = endTime - startTime;
console.log("Total time taken : " + timeTaken + " milliseconds");

In the above code:

  • Line 8: We call the performance.now() method. This will return the elapsed time since the time of origin. We store this value in the start variable.

  • Line 10: We call the test() function.

  • Line 12: We call the performance.now() method to get the current elapsed time since the time of origin.

  • Line 13: We subtract this value from the value obtained at the start. This will give the time taken to execute the test() function.

  • Line 15: We print the time taken to execute the test() function.

Note: The performance.now() method is the most efficient way to calculate the execution time because we can calculate the execution time with microsecond precision.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

What does performance.now() return?

A)

The current time

B)

The timestamp in milliseconds, including fractions

C)

The total execution time of the page

D)

The time taken by the last function

Question 1 of 20 attempted

Conclusion

We learned three primary methods for measuring execution time: Date.now(), performance.now(), and console.time() and console.timeEnd(). By incorporating these methods into our development workflow, we can significantly improve the performance of our applications, ensuring a better experience for our users. Now that we understand how to measure execution time, we can make informed decisions to enhance our JavaScript code and achieve our performance goals.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to check the time of a function

To check the time taken by a function in JavaScript, you can use various methods. One common approach is to use the Date.now() method to get the current time before and after the function execution, then calculate the difference:

let startTime = Date.now();
myFunction(); // Replace with the function you want to measure
let endTime = Date.now();
let timeTaken = endTime - startTime;
console.log("Time taken: " + timeTaken + " milliseconds");

Alternatively, you can use console.time() and console.timeEnd() for a simpler approach:

console.time("Execution Time");
myFunction(); // Replace with the function you want to measure
console.timeEnd("Execution Time");

How to calculate time in JavaScript

To calculate time in JavaScript, you can use the built-in Date object or the performance API. Here are two methods:

  • Using the Date object: You can create a new Date instance and retrieve the time in milliseconds since January 1, 1970:
    let currentTime = new Date().getTime(); // Returns the current time in milliseconds
    
  • Using performance.now(): For high-resolution time measurements, use performance.now(), which gives you time in milliseconds with a precision of up to microseconds:
    let start = performance.now();
    // Your code to measure
    let end = performance.now();
    let timeTaken = end - start;
    console.log("Time taken: " + timeTaken + " milliseconds");
    

How to execute a function at a specific time in JavaScript

To execute a function at a specific time in JavaScript, you can use setTimeout() or setInterval() functions.

  • Using setTimeout(): This method allows you to execute a function after a specified delay (in milliseconds):
    setTimeout(() => {
        myFunction(); // Replace with the function you want to execute
    }, 2000); // Executes myFunction after 2000 milliseconds (2 seconds)
    
  • Using setInterval(): If you want to execute a function repeatedly at specific intervals, use setInterval():
    let intervalId = setInterval(() => {
        myFunction(); // Replace with the function you want to execute
    }, 3000); // Executes myFunction every 3000 milliseconds (3 seconds)
    
    // To stop the interval, you can call clearInterval(intervalId);
    

These methods allow you to schedule function execution based on time intervals or delays.


Free Resources