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