summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2021-10-17 23:20:34 (GMT)
committerGitHub <noreply@github.com>2021-10-17 23:20:34 (GMT)
commit54a4e1b53a18f0c7420ba03de9608194c4413fc2 (patch)
tree3ee17b6bacf11400f605fcf972b687e39a2f64df
parentb3f0ceae919c1627094ff628c87184684a5cedd6 (diff)
downloadcpython-54a4e1b53a18f0c7420ba03de9608194c4413fc2.zip
cpython-54a4e1b53a18f0c7420ba03de9608194c4413fc2.tar.gz
cpython-54a4e1b53a18f0c7420ba03de9608194c4413fc2.tar.bz2
Improve multiserver queue recipe (GH-29012)
-rw-r--r--Doc/library/random.rst11
1 files changed, 6 insertions, 5 deletions
diff --git a/Doc/library/random.rst b/Doc/library/random.rst
index 0ac0fe7..36f232d 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)])