Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to check a function is defined in JavaScript ?
Next article icon

How to measure time taken by a function to execute using JavaScript ?

Last Updated : 18 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

This article will show how to measure the time taken by a function to execute using Javascript.

To measure the time taken by a function to execute we have three methods:

Table of Content

  • Using the Using Date Object
  • Using the performance.now() method
  • Using the console.time() method

Method 1: Using the Using Date Object

We can use the Date object to calculate the time taken by a function. we are using getTime() method from the Date object and then we calculate the average time taking by a function to execute.

Syntax:

// Get current time in milliseconds Start = new Date().getTime();   // Your function or code block here  end = new Date().getTime();

// Calculate execution time in milliseconds executionTime = endTime - startTime;

Example: This example explains the above-used approach.

HTML




<!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 time taken by
          the function. The output would be displayed on
          the console.
    </p>
    <button onclick="measurePerformance()">
        Click to check
    </button>
    <script type="text/javascript">
        function measurePerformance() {
           
              // Get current time in milliseconds
            const startTime = new Date().getTime();
            exampleFunction();
            const endTime = new Date().getTime();
            const timeTaken = endTime - startTime;
            console.log("Function took " + timeTaken + " milliseconds");
        }
 
        function exampleFunction() {
            for (let i = 0; i < 1000; i++) {
                console.log('Hello Geeks');
            }
        }
    </script>
</body>
   
</html>
 
 

Output:

Method 2: Using the performance.now() method

The now() method of the performance interface returns a high-resolution timestamp whenever it is called during the program. The time can be measured by getting the starting time before the function and the ending time after the function and then subtracting both of them. This gives the time elapsed for the function. 

Syntax: This example explains the above-used approach.

start = performance.now(); function_to_call();  end = performance.now();

Example: This example explains the above-used approach.

html




<!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 time
    taken by the function. The output would
    be displayed on the console.
</p>
 
<button onclick="measurePerformance()">
    Click to check
</button>
 
<script type="text/javascript">
    function measurePerformance() {
        start = performance.now();
        exampleFunction();
        end = performance.now();
        timeTaken = end - start;
        console.log("Function took " +
                timeTaken + " milliseconds");
    }
     
    function exampleFunction() {
        for (i = 0; i < 1000; i++) {
            console.log('Hello Geeks');
        }
    }
</script>
   
</body>
</html>
 
 

Output:

Method 3: Using the console.time() method.

The time() and timeEnd() methods of the Console object could be used as a timer to measure the time taken between these two methods. It takes a label parameter that could be used to distinguish between multiple timers. Whenever the timeEnd() method is called, the timer is stopped and the time output is given to the console. 

Syntax:

console.time('label'); function_to_call(); console.timeEnd('label');

Example: This example explains the above approach.

html




<!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 time
    taken by the function. The output would
    be displayed on the console.
</p>
 
<button onclick="measurePerformance()">
    Click to check
</button>
 
<script type="text/javascript">
    function measurePerformance() {
        console.time('function1');
        exampleFunction();
        console.timeEnd('function1');
    }
     
    function exampleFunction() {
        for(i= 0;i <1000; i++) {
            console.log('Hello Geeks');
        }
    }
</script>
   
</body>
</html>
 
 

Output:



Next Article
How to check a function is defined in JavaScript ?
author
sayantanm19
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-functions
  • JavaScript-Questions

Similar Reads

  • What is a typical use case for anonymous functions in JavaScript ?
    In this article, we will try to understand what exactly an Anonymous function is, and how we could declare it using the syntax provided in JavaScript further we will see some examples (use-cases) where we can use anonymous functions to get our results in the console. Before proceeding with the examp
    4 min read
  • How to check whether a number is NaN or finite in JavaScript ?
    When working with numbers in JavaScript, it's important to know how to determine if a value is NaN (Not-a-Number) or finite. This knowledge is crucial for data validation, error handling, and ensuring your code behaves as expected. In this article, we will see how to check whether the number is NaN
    3 min read
  • How to Encode and Decode a URL in JavaScript?
    Encoding and decoding URLs in JavaScript is essential for web development, especially when making GET requests with query parameters. This process ensures special characters in URLs are correctly interpreted by the server. For instance, spaces are converted to %20 or + in URLs. This guide covers how
    5 min read
  • How to declare the optional function parameters in JavaScript ?
    Declaring optional function parameters in JavaScript means defining function parameters that aren't required when the function is called. You can assign default values to these parameters using the = syntax, so if no argument is provided, the default value is used instead. These are the following ap
    3 min read
  • How to get the javascript function parameter names/values dynamically ?
    In this article, we are given any arbitrary JavaScript function and the task is to return the parameter names of the function. Approach: JavaScript contains a method called toString() which is used to represent a function code in its string representation. This method is used to get the parameter na
    2 min read
  • How To Include a JavaScript File in Another JavaScript File?
    The import and export syntax available in ES6 (ECMAScript 2015) module is used to include a JavaScript file in another JavaScript file. This approach is the most modern and recommended way to share code between JavaScript files. It allows you to break your code into smaller modules and then import t
    4 min read
  • How to override a JavaScript function ?
    In this article, we are given an HTML document and the task is to override the function, either a predefined function or a user-defined function using JavaScript. Approach: When we run the script then Fun() function is called. After clicking the button the GFG_Fun() function is called and this funct
    2 min read
  • Using the function* Declaration in JavaScript
    The function* declaration is used to define a generator that returns a Generator object. Generators are very powerful for asynchronous programming as they aim to resolve callback problems. In a generator, the yield keyword is used instead of return. The yield statement suspends the function’s execut
    2 min read
  • What is the difference between call and apply in JavaScript ?
    JavaScript call() Method: It calls the method, taking the owner object as an argument. The keyword this refers to the 'owner' of the function or the object it belongs to. We can call a method that can be used on different objects. Syntax: object.objectMethod.call( objectInstance, arguments ) JavaScr
    2 min read
  • How to find out the caller function in JavaScript?
    In this article, we see the methods to find out the caller function in Javascript. Sometimes, the developer may want to modify how a function works on the basis of its caller function. To find out the caller function name, we will use the Function object's caller property. Property: Function.caller
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences