Chapter 01 · Counting steps01 / 21

Why not just time it?

You wrote a function that finds the largest number in an array, and you want to know if it's fast. The obvious move is to time it. Here the same function scans the same 10 million numbers on three machines.

The stopwatches disagree: about 6 ms on the server, 14 ms on the laptop, 27 ms on the same laptop on battery. A timing describes one machine on one day, not the code.

Now look at the counters. Every machine made exactly 10,000,000 comparisons, one per number. That count belongs to the code itself, so it's what we'll measure.

The timings are illustrative, but the spread is realistic: CPU generation, power settings, other programs and even temperature change clock time. Benchmarks still matter; they just answer a different question.

findMax.jsin the real world
function findMax(arr) {
let max = -Infinity;
for (const x of arr) { // one comparison per element
if (x > max) max = x;
}
return max;
}
 
console.time('findMax');
findMax(numbers); // 10,000,000 numbers
console.timeEnd('findMax'); // 6 ms? 14 ms? depends on the machine