Skip to content

Instantly share code, notes, and snippets.

@mscdex
Forked from xk/bench.js
Created April 12, 2012 17:23
Show Gist options
  • Save mscdex/2369318 to your computer and use it in GitHub Desktop.
Save mscdex/2369318 to your computer and use it in GitHub Desktop.
When threads_a_gogo beats node 2 to 1.... or does it?
/*
$ node bench.js
Threads_a_gogo JS thread -> 3039 (ms) 298607040
Node's main JS thread -> 4677 (ms) 298607040
Ratio: 1.54 times faster than main JS thread
New, separate VM -> 3065 (ms) 298607040
Ratio: 1.01 times faster than new VM
*/
var vm = require('vm');
function fib (n) {
return (n < 2) ? 1 : fib(n-2)+ fib(n-1);
}
function loop (n) {
var r= 0;
while (n--) r+= fib(35);
return r;
}
function cb (err, data) {
var save_t= t= Date.now()- t;
console.log("Threads_a_gogo JS thread -> ", t, '(ms) ', data);
thread.destroy();
t= Date.now();
data= loop(20);
t= Date.now()- t;
console.log("Node's main JS thread -> ", t, '(ms) ', data);
console.log('Ratio: '+ (t/save_t).toFixed(2)+ ' times faster than main JS thread');
t = Date.now();
this.loop = loop;
data = vm.runInNewContext("function fib (n) { return (n < 2) ? 1 : fib(n-2)+ fib(n-1); } function loop (n) { var r= 0; while (n--) r+= fib(35); return r; } loop(20)", 'looper');
t = Date.now() - t;
console.log("New, separate VM -> ", t, '(ms) ', data);
console.log('Ratio: '+ (t/save_t).toFixed(2)+ ' times faster than new VM');
}
var thread= require('threads_a_gogo').create().eval(fib).eval(loop);
var t= Date.now();
thread.eval('loop(20)', cb);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment