// 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
*/