不调用simpy库的排队模型系统仿真python代码
时间: 2023-12-06 10:44:15 浏览: 116
下面是一个简单的排队模型系统仿真python代码,不使用SimPy库:
```python
import random
class Customer:
def __init__(self, id, arrival_time):
self.id = id
self.arrival_time = arrival_time
self.service_start_time = None
self.service_end_time = None
def __str__(self):
return f"Customer {self.id}"
class Queue:
def __init__(self):
self.customers = []
def add_customer(self, customer):
self.customers.append(customer)
def next_customer(self):
if len(self.customers) > 0:
return self.customers.pop(0)
else:
return None
class Server:
def __init__(self):
self.current_customer = None
self.total_service_time = 0
self.total_customers_served = 0
def is_busy(self):
return self.current_customer is not None
def start_service(self, customer, current_time):
self.current_customer = customer
self.current_customer.service_start_time = current_time
def end_service(self, current_time):
self.current_customer.service_end_time = current_time
self.total_service_time += current_time - self.current_customer.service_start_time
self.total_customers_served += 1
self.current_customer = None
def run_simulation(num_customers, interarrival_mean, service_time_mean):
server = Server()
queue = Queue()
customers = []
for i in range(num_customers):
interarrival_time = random.expovariate(1.0/interarrival_mean)
arrival_time = 0 if i == 0 else customers[i-1].arrival_time + interarrival_time
service_time = random.expovariate(1.0/service_time_mean)
customers.append(Customer(i+1, arrival_time))
queue.add_customer(customers[i])
print(f"Customer {i+1} arrives at time {arrival_time:.2f}")
current_time = 0
while len(customers) > server.total_customers_served:
if not server.is_busy():
next_customer = queue.next_customer()
if next_customer is not None:
server.start_service(next_customer, current_time)
print(f"Customer {next_customer.id} starts service at time {current_time:.2f}")
else:
if current_time >= server.current_customer.service_start_time + service_time:
server.end_service(current_time)
print(f"Customer {server.current_customer.id} ends service at time {current_time:.2f}")
current_time += 0.1
avg_service_time = server.total_service_time / server.total_customers_served
print(f"\nSimulation results:\nTotal customers served: {server.total_customers_served}")
print(f"Average service time: {avg_service_time:.2f}")
run_simulation(10, 1, 2)
```
这个代码模拟了一个简单的排队系统,每个顾客的到达时间和服务时间都是随机的。在模拟的过程中,程序将打印出每个顾客的到达时间、开始服务时间和结束服务时间,以及模拟结果,包括服务的总时间和平均服务时间。
阅读全文