[Python-checkins] Improve multiserver queue recipe (GH-29012)
rhettinger
webhook-mailer at python.org
Sun Oct 17 19:20:54 EDT 2021
https://github.com/python/cpython/commit/54a4e1b53a18f0c7420ba03de9608194c4413fc2
commit: 54a4e1b53a18f0c7420ba03de9608194c4413fc2
branch: main
author: Raymond Hettinger <rhettinger at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2021-10-17T18:20:34-05:00
summary:
Improve multiserver queue recipe (GH-29012)
files:
M Doc/library/random.rst
diff --git a/Doc/library/random.rst b/Doc/library/random.rst
index 0ac0fe72dc392..36f232dc319e4 100644
--- a/Doc/library/random.rst
+++ b/Doc/library/random.rst
@@ -503,7 +503,7 @@ between the effects of a drug versus a placebo::
Simulation of arrival times and service deliveries for a multiserver queue::
- from heapq import heappush, heappop
+ from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles
@@ -515,14 +515,15 @@ Simulation of arrival times and service deliveries for a multiserver queue::
waits = []
arrival_time = 0.0
servers = [0.0] * num_servers # time when each server becomes available
- for i in range(100_000):
+ heapify(servers)
+ for i in range(1_000_000):
arrival_time += expovariate(1.0 / average_arrival_interval)
- next_server_available = heappop(servers)
+ next_server_available = servers[0]
wait = max(0.0, next_server_available - arrival_time)
waits.append(wait)
- service_duration = gauss(average_service_time, stdev_service_time)
+ service_duration = max(0.0, gauss(average_service_time, stdev_service_time))
service_completed = arrival_time + wait + service_duration
- heappush(servers, service_completed)
+ heapreplace(servers, service_completed)
print(f'Mean wait: {mean(waits):.1f} Max wait: {max(waits):.1f}')
print('Quartiles:', [round(q, 1) for q in quantiles(waits)])
More information about the Python-checkins
mailing list