Permalink
Browse files

event emitter: some benchmarking

  • Loading branch information...
1 parent dc8b488 commit fa5279d77bf93a5a59c2516849103955877b4a0e @pgte committed Jun 5, 2012
Showing with 132 additions and 0 deletions.
  1. +132 −0 benchmark/event_emitter.js
View
@@ -0,0 +1,132 @@
+var EventEmitter = require('events').EventEmitter,
+ assert = require('assert');
+
+
+function oneEventOneListener(max, done) {
+ var ee = new EventEmitter();
+ var eventCount = 0;
+
+ ee.on('myevent', function() {
+ eventCount ++;
+ });
+
+ for (var i = 0 ; i < max ; i ++) {
+ ee.emit('myevent');
+ }
+
+ assert.equal(eventCount, max);
+ done();
+}
+
+function oneEventFourListeners(max, done) {
+ var ee = new EventEmitter();
+ var eventCount = 0;
+
+ for ( var l = 0 ; l < 4 ; l ++) {
+ ee.on('myevent', function() {
+ eventCount ++;
+ });
+ }
+
+ for (var i = 0 ; i < max ; i ++) {
+ ee.emit('myevent');
+ }
+
+ assert.equal(eventCount, max * 4);
+ done();
+}
+
+function twoEventsTwoListeners(max, done) {
+ var ee = new EventEmitter();
+ max = max / 2;
+ var eventCount = 0;
+
+ for ( var l = 0 ; l < 2 ; l ++) {
+ ee.on('myevent' + l, function() {
+ eventCount ++;
+ });
+ }
+
+ for ( var j = 0 ; j < 2 ; j ++) {
+ for (var i = 0 ; i < max ; i ++) {
+ ee.emit('myevent' + j);
+ }
+ }
+
+ assert.equal(eventCount, max * 2);
+ done();
+}
+
+function twoEventsFourListeners(max, done) {
+ var ee = new EventEmitter();
+ max = max / 2;
+ var eventCount = 0;
+
+ for ( var l = 0 ; l < 2 ; l ++) {
+ for ( var m = 0 ; m < 2 ; m ++) {
+ ee.on('myevent' + l, function() {
+ eventCount ++;
+ });
+ }
+ }
+
+ for ( var j = 0 ; j < 2 ; j ++) {
+ for (var i = 0 ; i < max ; i ++) {
+ ee.emit('myevent' + j);
+ }
+ }
+
+ assert.equal(eventCount, max * 4);
+ done();
+}
+
+//
+// Test definitions
+//
+var tests = [
+ { name: '1 event, 1 listener'
+ , loop: 1e8
+ , fn: oneEventOneListener }
+, { name: '1 event, 4 listeners'
+ , loop: 1e8
+ , fn: oneEventFourListeners }
+, { name: '2 events, 2 listeners'
+ , loop: 1e8
+ , fn: twoEventsTwoListeners }
+, { name: '2 events, 4 listeners'
+ , loop: 1e8
+ , fn: twoEventsFourListeners }
+];
+
+function run(i) {
+
+ if (i >= tests.length) {
+ console.log('All done.');
+ return;
+ }
+
+ var test = tests[i];
+ var testFunc = test.fn;
+ var loop = test.loop;
+
+ var start = Date.now();
+
+ testFunc(loop, function() {
+ var end = Date.now();
+ var diff = end - start;
+ var seconds = diff / 1000;
+ var rate = Math.round(loop / seconds);
+ console.log(test.name + ': Ellapsed: ' + seconds + 's. Rate: ' + rate + ' emits/sec.');
+ process.nextTick(function() {
+ run(i + 1);
+ });
+ });
+}
+
+if (process.argv[2]) {
+ tests = tests.filter(function(test) {
+ return test.name === process.argv[2];
+ });
+}
+
+run(0);

0 comments on commit fa5279d

Please sign in to comment.