How to measure a function execution time in TypeScript

3 Answers

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

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

const start: number = performance.now();

mul(20, 8000000); 

const end: number = performance.now(); 

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



/*
run:

Function execute time: 4 milliseconds

*/

 



answered Aug 5, 2024 by avibootz
edited 10 hours ago by avibootz
0 votes
function mul(a: number, n: number) {
    let total = 0; 
    
    for (let i: number = 0; i < n; i++)
        total += a;
    
    return total;
}

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

const start = new Date().getTime();

mul(20, 8000000); 

const elapsed = new Date().getTime() - start;

console.log('Function execute time: ' + elapsed + ' milliseconds');



/*
run:

Function execute time: 5 milliseconds

*/

 



answered Aug 5, 2024 by avibootz
edited 10 hours ago by avibootz
0 votes
// Measuring function execution time in 
// TypeScript using a reusable Timer (milliseconds + seconds)

// ---------------------------
// Reusable Timer class
// ---------------------------
class Timer {
    private start: number = 0;
    private end: number = 0;

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

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

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

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

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

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

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

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

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



/* 
run:

Execution time: 123.53488100000004 ms
Execution time: 0.12353488100000004 seconds

*/

 



answered 10 hours ago by avibootz
...