How to measure a function execution time in Node.js

2 Answers

0 votes
function mul(a, n) {
    let total = 0; 
    
    for (let i = 0; i < n; i++)
        total += a;
    
    return total;
}

// performance.now() method returns a high-resolution timestamp in milliseconds

const start = performance.now();

mul(20, 3000); 

const end = performance.now(); 

console.log('Function execute time: ' + (end - start) + ' milliseconds');



/*
run:

Function execute time: 0.2610209999838844 milliseconds

*/

 



answered Aug 5, 2024 by avibootz
edited Aug 5, 2024 by avibootz
0 votes
// Measuring function execution time in 
// Node.js using a reusable Timer (milliseconds + seconds)

// ---------------------------
// Reusable Timer class
// ---------------------------
class Timer {
    constructor() {
        this.start = 0n; // bigint nanoseconds
        this.end = 0n;
    }

    // Start the timer
    startTimer() {
        this.start = process.hrtime.bigint();
    }

    // Stop the timer
    stopTimer() {
        this.end = process.hrtime.bigint();
    }

    // Return elapsed time in milliseconds
    elapsedMilliseconds() {
        return Number(this.end - this.start) / 1_000_000;
    }

    // Return elapsed time in seconds
    elapsedSeconds() {
        return Number(this.end - this.start) / 1_000_000_000;
    }
}

// ---------------------------
// Function to measure
// ---------------------------
function work() {
    let sum = 0;
    for (let i = 0; i < 100_000_000; i++) {
        sum += i;
    }
}

// ---------------------------
// Main program
// ---------------------------
const t = new Timer();

t.startTimer();
work();
t.stopTimer();

const ms = t.elapsedMilliseconds();
const sec = t.elapsedSeconds();

console.log("Execution time:", ms, "ms");
console.log("Execution time:", sec, "seconds");


/* 
run:

Execution time: 53.517752 ms
Execution time: 0.053517752 seconds

*/

 



answered 10 hours ago by avibootz
...