Code: Select all
import random
import time
from concurrent.futures import (
InterpreterPoolExecutor,
ProcessPoolExecutor,
ThreadPoolExecutor,
Executor,
)
from os import process_cpu_count
def cpus() -> int:
"""
Get the number of available CPUs minus one but with a minimum of 2
"""
ncpus = process_cpu_count() or 2
return ncpus - 1 if ncpus > 3 else 2
def func(_: int) -> list[int]:
return [random.randint(1, 10) for _ in range(10_000)]
def process(pool: Executor) -> None:
start = time.perf_counter()
with pool() as e:
for _ in e.map(func, range(cpus())):
pass
duration = time.perf_counter() - start
print(pool.__name__, f"{duration=:.4f}s")
if __name__ == "__main__":
for pool_executor in (
InterpreterPoolExecutor,
ProcessPoolExecutor,
ThreadPoolExecutor,
):
process(pool_executor)
Code: Select all
with pool() as e:
Vermutlich liegt das daran, dass der Typhinweis von Executor falsch ist.
Wie überwinde ich das?
Mobile version