我使用simpy
库python
创建了一个简单的仿真环境,其中只有一个生成器和两个使用者。生成器以随机速率以及另一个随机数生成请求。该随机数将传递给第一个使用者,后者使用该随机数作为其处理时间。相同的随机数从第一个使用者传递到第二个使用者,后者再次将其用作其处理时间。当有更多的消费者时,此实现的代码(如下所述)似乎不可行,因为我将不得不添加更多的consumer_()
方法。我希望能够以更可行的方式模拟相同的设置。感谢有关如何执行此任务的一些指导。谢谢!
import pandas
import simpy
import numpy as np
import scipy.stats as st
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import random
RANDOM_SEED = 42
NEW_REQUEST = 100
s1_totalQueueLength = 0
s1_sumWaitingTime = 0.0
s2_totalQueueLength = 0
s2_sumWaitingTime = 0.0
def generator(env, number, s1_counter, s2_counter):
for i in range(number):
r = random.expovariate(75.00)
s1 = server_one(env, i, s1_counter, s2_counter, r)
env.process(s1)
t = random.expovariate(15)
yield env.timeout(t)
def consumer_1(env, i, s1_counter, s2_counter, s3_counter, r):
global s1_totalQueueLength
global s1_sumWaitingTime
global arrivalTime
arrive = env.now
arrivalTime = arrive
with s1_counter.request() as req:
results = yield req
wait = env.now - arrive
yield env.timeout(r)
s2 = consumer_2(env, i, s2_counter, s3_counter, tib)
env.process(s2)
s1_totalQueueLength = s1_totalQueueLength + len(s1_counter.queue)
s1_sumWaitingTime = s1_sumWaitingTime + wait
if i > 0:
print("Server 1: average queue length = " + str(s1_totalQueueLength/i) + " average waiting time = " + str(s1_sumWaitingTime/i))
file1.write(str(wait) + "\n")
def consumer_2(env, i, s2_counter, s3_counter, tib):
global s2_totalQueueLength
global s2_sumWaitingTime
print("S2 received " + str(tib)+" from Server One")
arrive = env.now
with s2_counter.request() as req:
results = yield req
wait = env.now - arrive
yield env.timeout(tib)
s2_totalQueueLength = s2_totalQueueLength + len(s2_counter.queue)
s2_sumWaitingTime = s2_sumWaitingTime + wait
if i > 0:
print("Server 2: average queue length = " + str(s2_totalQueueLength / i) + " average waiting time = " + str(
s2_sumWaitingTime / i))
file2.write(str(wait)) + "\n")
random.seed(RANDOM_SEED)
env = simpy.Environment()
file1 = open("c1.csv", "w")
file1.write("Waiting_time" + "\n")
file2 = open("c2.csv", "w")
file2.write("Waiting_time" + "\n")
# Start processes and run
s1_counter = simpy.Resource(env, capacity=1)
s2_counter = simpy.Resource(env, capacity=1)
env.process(generator(env, NEW_REQUEST, s1_counter, s2_counter))
env.run()