{

How to measure time taken by function to execute Javascript


How to measure time taken by function to execute Javascript example

In this blog post, JavaScript offers ways to calculate measure (elapsed) time taken by a function execution in JavaScript and NodeJS.

Sometimes, we need to know function execution time while profiling a JavaScript application to improve performance.

It helps the developer to pinpoint the problem method for the time taken.

Time elapse taken in JavaScript. Measure time in NodeJS.

How to measure time taken for function execution using console object

Console object is an inbuilt JavaScript object useful for getting debugging information during development.

We have to two below methods to measure the time time() method initializing timer task timeEnd() method stop timer task.

These two methods have a string argument that contains the timer task name. Configure multiple timer tasks using console objects to print the information.

Example code:

start = console.time("callAPITimer");

callAPI();
console.timeEnd('callAPITimer')

function callAPI() {

    for (i = 0, i < 10; i++;) {

        $.ajax({
            url: 'my-json-server.typicode.com/user/repo/posts/1',
            success: function() {
                console.log("success");
            },
            error: function(err) {
                console.log("error", err);

            }
        });
    }
}

Time taken for function execution using performance

performance is an object which provides performance-related metrics of a page in a browser and server-side, It has now() method to return the current timestamp in milliseconds.

performance instance can be used on client JavaScript and server-side NodeJS applications.

Syntax

performance.now() //22.584999998798594

Time elapsed on the client web page

on the Client side, We can use in the script tag to calculate the time take for the function execution

In the function - processIt, REST API is called for 10 times using ajax . Taken the time before function call and after call return time taken by subtracting from the first call to second call

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Time taken </title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <script>
        start = performance.now();

        processIt();
        end = performance.now();
        timeTaken = end - start;
        console.log('time elapsed', timeTaken);

        function processIt() {

            for (i = 0, i < 10; i++;) {
                $.ajax({
                    url: 'my-json-server.typicode.com/user/repo/posts/1',
                    success: function() {
                        console.log("success");
                    },
                    error: function(err) {
                        console.log("error", err);

                    }
                });
            }
        }
    </script>
</head>
<body>
</body>
</html>

And output you see in the console.

time elapsed 0.11499998799990863

if you use performance object on the Server-side in the NodeJS application, you will see the following error Fixing ReferenceError: performance is not defined

Let us see how we can use performance in the Nodejs application and solve the above error.

find time measured in Nodejs

performance instance is available in perf_hooks module since the 8.6 version

first import perf_hooks into NodeJS code using object destructing feature

const {performance} = require('perf_hooks');
 or 
const performance= require('perf_hooks').performance;

Complete example in Nodejs:

const { performance } = require('perf_hooks');

const start = performance.now();

processIt();

const end = performance.now();
let timeElapsed = end - start
console.log("time taken", timeElapsed); // 3.158299997448921

Conclusion

To summarize,

This posts covers time taken by function execution in javascript. using console end timeEnd,Performance now function in perf_hooks in nodejs

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.