Skip to content

Instantly share code, notes, and snippets.

@senderista
Created August 27, 2015 05:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save senderista/625dda440ef0ed281378 to your computer and use it in GitHub Desktop.
Save senderista/625dda440ef0ed281378 to your computer and use it in GitHub Desktop.
A simple processor-sharing queue simulator in node.js
var PoissonProcess = require('poisson-process');
var sleep = require('sleep');
var http = require('http');
var port = process.env.PORT || 1337;
var TIMESLICE_MILLIS = 1;
var MEAN_SLEEP_MILLIS = 500;
function sleep_for_timeslice(total_ms, ms_left, req_timestamp, res) {
if (ms_left > 0) {
sleep.usleep(TIMESLICE_MILLIS*1000);
setTimeout(sleep_for_timeslice, TIMESLICE_MILLIS, total_ms, ms_left-TIMESLICE_MILLIS, req_timestamp, res);
} else {
var cur_timestamp = (new Date).getTime();
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('slept for ' + total_ms + 'ms out of total ' + (cur_timestamp-req_timestamp) + 'ms\n');
}
}
http.createServer(function (req, res) {
// sleep for exponentially distributed time in milliseconds
var sleep_millis = Math.round(PoissonProcess.sample(MEAN_SLEEP_MILLIS));
var req_timestamp = (new Date).getTime();
sleep_for_timeslice(sleep_millis, sleep_millis, req_timestamp, res);
}).listen(port);
console.log('Server running on port %s', port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment