Skip to content

Instantly share code, notes, and snippets.

@francium
Created September 20, 2018 01:32
Show Gist options
  • Save francium/4ff5790e25c07a2d56296c4ceb912747 to your computer and use it in GitHub Desktop.
Save francium/4ff5790e25c07a2d56296c4ceb912747 to your computer and use it in GitHub Desktop.
Two Queue simluation example
import logging
from math import inf, log
from random import random as rand
log_format ='%(asctime)s.%(msecs)03d %(levelname)8s [%(module)s %(funcName)s] %(message)s'
datefmt ="%Y-%m-%d %H:%M:%S"
logger_level = logging.WARN
logging.basicConfig(level=logger_level, format=log_format, datefmt=datefmt)
logger = logging.getLogger(__name__)
def min2(arr):
v = min(arr)
i = arr.index(v)
return v, i
def mean(arr):
return sum(arr) / len(arr)
def list_subtract(a, b):
return list(map(
lambda tup: tup[0] - tup[1],
zip(a, b)))
def two_queue(lambda_, mu1, mu2, simtime):
logger.info('Simulation params')
logger.info('=================')
logger.info(f'lambda: {lambda_}')
logger.info(f'mu_1: {mu1}')
logger.info(f'mu_2: {mu2}')
logger.info(f'simulation time: {simtime}')
t = 0
q = [0, 0]
ttne = [-log(rand()) / lambda_, inf, inf]
arrivals = 0
departures = 0
arrival_times = []
depature_times = []
while t < simtime:
min_value, queue_index = min2(ttne)
logger.debug(f'next event in {min_value} at queue {queue_index + 1}')
t += min_value
ttne = [i - min_value for i in ttne]
if queue_index == 0:
logger.debug('new arrival at queue 1')
arrivals += 1
arrival_times.append(t)
q[0] += 1
ttne[0] = -log(rand()) / lambda_
if ttne[1] == inf:
ttne[1] = -log(rand()) / mu1
elif queue_index == 1:
logger.debug('event moved to queue 2')
q[0] -= 1
q[1] += 1
if q[0] > 0:
ttne[1] = -log(rand()) / mu1
else:
ttne[1] = inf
if ttne[2] == inf:
ttne[2] = -log(rand()) / mu2
else:
logger.debug('event departure')
q[1] -= 1
departures += 1
depature_times.append(t)
if q[1] > 0:
ttne[2] = -log(rand()) / mu2
else:
ttne[2] = inf
logger.info(f'simtime: {t}')
logger.debug(f'ttne: {ttne}')
throughput = departures / t
avg_response = mean(
list_subtract(depature_times, arrival_times[:departures]))
# throughput = departures
# avg_response = [depature_times[1:10], arrival_times[1:10]]
return throughput, avg_response
if __name__ == '__main__':
print(two_queue(5, 2, 3, 1000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment