Estimate CPU speed by timing how long it takes to decrement a variable millions of times:
const runs = 150000000;
const start = performance.now(); // in ms, usually with 100us resolution
for (let i = runs; i>0; i--) {}
const end = performance.now();
const ms = end - start;
const cyclesPerRun = 2;
const speed = (runs / ms / 1000000) * cyclesPerRun;
console.log(`Time: ${Math.round(ms)/1000}s, estimated speed: ${Math.round(speed*10)/10} GHz`);
* cyclesPerRun
is a very rough way to map "subtractions per second" to clock speed and it varies a lot across browsers (because their JavaScript engines might optimize the code differently) and CPUs (because they might be able to pipeline more instructions, they might ramp up their frequency faster, etc.). You might be better off just using runs / ms
as a generic "CPU speed" parameter instead of trying to estimate the clock speed in GHz with cyclesPerRun
.
You can also estimate cyclesPerRun
yourself by running the code above on a CPU you know the clock speed of and then doing this:
const knownSpeed = 3.2; // GHz
const estimatedCyclesPerRun = knownSpeed / (runs/ms/1000000);
console.log("cyclesPerRun = " + estimatedCyclesPerRun);
Also this benchmark depends on the number of browser tabs the user has open or if some other program (like a video game) is already using the computer's resources, etc.