[Python-checkins] Improve multiserver queue recipe (GH-29012) (GH-29014)
rhettinger
webhook-mailer at python.org
Mon Oct 18 01:25:00 EDT 2021
https://github.com/python/cpython/commit/cb34c1ee1b1afe9165a26f1428362ea4bc6afe26
commit: cb34c1ee1b1afe9165a26f1428362ea4bc6afe26
branch: 3.9
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2021-10-18T00:24:51-05:00
summary:
Improve multiserver queue recipe (GH-29012) (GH-29014)
files:
M Doc/library/random.rst
diff --git a/Doc/library/random.rst b/Doc/library/random.rst
index f2d6749422a15..758d1292086e5 100644
--- a/Doc/library/random.rst
+++ b/Doc/library/random.rst
@@ -502,7 +502,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, median, stdev
@@ -514,14 +514,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}. Stdev wait: {stdev(waits):.1f}.')
print(f'Median wait: {median(waits):.1f}. Max wait: {max(waits):.1f}.')
More information about the Python-checkins
mailing list