How to measure a function execution time in JavaScript

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(10, 3000); 

const end = performance.now(); 

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



/*
run:

Function execute time: 0.12034999951720238 milliseconds

*/

 



answered May 24, 2021 by avibootz
edited Aug 5, 2024 by avibootz
0 votes
// Measuring function execution time in 
// JavaScript using a reusable Timer (milliseconds + seconds)

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

    // Start the timer
    startTimer() {
        this.start = performance.now();  // high‑precision timer
    }

    // Stop the timer
    stopTimer() {
        this.end = performance.now();
    }

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

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

// ---------------------------
// 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: 144.767161 ms
Execution time: 0.14476716099999998 seconds

*/

 



answered 10 hours ago by avibootz
...