August 2018
Intermediate to advanced
366 pages
10h 14m
English
To run a future, we will need an executor (either ThreadPoolExecutor, ProcessPoolExecutor) and the futures we actually want to run. For the sake of our example, we will use a function that returns the time it takes to load a web page so we can benchmarks multiple websites to see which one is the fastest:
import concurrent.futures import urllib.request import time def benchmark_url(url): begin = time.time() with urllib.request.urlopen(url) as conn: conn.read() return (time.time() - begin, url) class UrlsBenchmarker: def __init__(self, urls): self._urls = urls def run(self, executor): futures = self._benchmark_urls(executor) fastest = min([ future.result() for future in concurrent.futures.as_completed(futures) ]) print('Fastest ...