Created
August 27, 2015 05:20
-
-
Save senderista/625dda440ef0ed281378 to your computer and use it in GitHub Desktop.
A simple processor-sharing queue simulator in node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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