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