Time Taken by Function

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to measure the time taken by a function to execute using JavaScript. We will use the console.time() and console.timeEnd() methods to measure the difference between the start and end times of a function and determine how long it took to execute. This skill is useful for optimizing code and improving performance in web development.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("`Debugging`") subgraph Lab Skills javascript/variables -.-> lab-28647{{"`Time Taken by Function`"}} javascript/data_types -.-> lab-28647{{"`Time Taken by Function`"}} javascript/arith_ops -.-> lab-28647{{"`Time Taken by Function`"}} javascript/comp_ops -.-> lab-28647{{"`Time Taken by Function`"}} javascript/debugging -.-> lab-28647{{"`Time Taken by Function`"}} end

Measuring Time Taken by a Function

To measure the time taken by a function, use console.time() and console.timeEnd() to determine the difference between the start and end times.

Here's an example function called timeTaken that measures the time taken by a callback function:

const timeTaken = (callback) => {
  console.time("timeTaken");
  const result = callback();
  console.timeEnd("timeTaken");
  return result;
};

To use this function, simply pass in your callback as an argument. For example:

timeTaken(() => Math.pow(2, 10)); // Returns 1024, and logs: timeTaken: 0.02099609375ms

In the example above, the timeTaken function is used to measure the time taken to execute the Math.pow(2, 10) function call, which returns 1024. The console output will show the time taken in milliseconds (ms).

Summary

Congratulations! You have completed the Time Taken by Function lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like