How to measure time taken by function to execute in Javascript|Nodejs


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 an JavaScript application for performance improvements

This will be very useful to pin point the problem method for time taken.

Time elapse taken in JavaScript Measuring time in NodeJS.

How to measure time taken for function execution using console object

Console object is 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 has an string argument which can be name for timer task name. This is very useful while configuring multiple timer task using console object.

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 application.

Syntax

performance.now() //22.584999998798594

Time elapsed on client web page

on Client side, We can use in script tag to calculate 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 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 seen in the console

time elapsed 0.11499998799990863

if you use performance object in Server side i.e NodeJS application, you will see following error Fixing ReferenceError: performance is not defined

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

find time measured in Nodejs

performance instance is available in perf_hooks module since 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
Similar Posts