Skip to content

Instantly share code, notes, and snippets.

@peterbe
Created May 15, 2015 15:57
Show Gist options
  • Save peterbe/d42cdb884f8707c84906 to your computer and use it in GitHub Desktop.
Save peterbe/d42cdb884f8707c84906 to your computer and use it in GitHub Desktop.
var PI = Math.pi;
function f0(x) {
return PI / x;
}
function f1(x) {
if (x != 0) {
return PI / x;
} else {
return -1;
}
}
function f2(x) {
try {
return PI / x;
} catch(e) {
return -1;
}
}
function run(f) {
var t = process.hrtime();
for (var i=0; i<10000; i++) {
for (var j=1; j<100; j++) {
f(j);
}
}
t = process.hrtime(t);
return t[1] / 1000 / 1000 / 1000;
}
function choice(ops) {
return ops[Math.floor(Math.random() * ops.length)];
}
funcs = [f0, f1, f2];
times = {};
funcs.forEach(function(f) {
times[f.name] = [];
});
for (var i=0; i < 100; i++) {
f = choice(funcs);
times[f.name].push(run(f));
}
function sum(items) {
var t = 0;
for (var i=0; i<items.length; i++) {
t += items[i];
}
return t;
}
for (k in times) {
console.log(k, sum(times[k]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment