Skip to main content

Measuring Execution Time in Node.js: The Decorator Approach

ยท 2 min read
Samuel Joset

Hello everyone! Have you ever wondered, "How much time does this code actually take to execute?". If the answer is no... Well, you're going to start today! Measuring the execution time of an application is often necessary for considering improvements or for writing relevant logs.

Today, we are going to see how to obtain this information painlessly. And it's through a decorator that we are going to do it. Let's get started!

1. Our Tool: The Function Decoratorโ€‹

In a previous article, I already explained why decorators are a method of choice to enhance the capabilities of a function. We can add features to a function without modifying the initial code.

We are going to leverage this concept to create a simple decorator that will allow us to measure the execution time of our functions.

Let's take a look at our decorator:

const measureExecutionTime = (fn) => {
return (...args) => {
const start = Date.now();
const result = fn(...args);
const end = Date.now();
return { result, executionTime: end - start // time in ms };
};
};

Now, let's see how to apply it to an existing function:

const add = (a, b) => a + b;

const addWithExecutionTime = measureExecutionTime(add);

console.log(addWithExecutionTime(5, 7)); // displays { result: 12, executionTime: <execution time> }

In this example, we have an add function that adds two numbers. With our measureExecutionTime decorator, we get a new function, addWithExecutionTime. This improved function still adds two numbers, but it also returns the time it took to execute.

2. Handling Different Function Types: Synchronous and Asynchronousโ€‹

The function we created previously is simple and does the job, however, it has a problem: it does not handle asynchronous functions.

To remedy this issue, we will also create a second function that can be used to measure the execution time of an asynchronous function:

const measureExecutionTimeAsync = (fn) => {
return async (...args) => {
const start = Date.now();
const result = await fn(...args);
const end = Date.now();
return { result, executionTime: end - start // time in ms };
};
};

This function is very similar to the first one. The only difference being that the new function returns a promise instead of a classic data type.

3. Conclusionโ€‹

The article ends here. This function is simple, but don't confuse utility with complexity. It will be useful to you in all your Node.js development.