Skip to content

Instantly share code, notes, and snippets.

@amaciel81
Last active March 8, 2021 06:32
Show Gist options
  • Save amaciel81/f2c3650dd7a6c0f402d3de3e4f1c235a to your computer and use it in GitHub Desktop.
Save amaciel81/f2c3650dd7a6c0f402d3de3e4f1c235a to your computer and use it in GitHub Desktop.
import time
from contextlib import contextmanager
from typing import Any, List, Callable
@contextmanager
def timer():
start_time = time.time()
yield
elapsed_time = time.time() - start_time
print(f"Total time: {elapsed_time:.2f}s\n")
def cpu_worker(x: int, y: int) -> int:
result = 0
for number in range(1, x + 1):
if number % y == 0:
result +=1
def io_worker(time_sec: int) -> str:
time.sleep(time_sec)
return f"Waited for {time_sec}s..."
def serial_scheduler(instances: int, worker: Callable, args: List[Any]) -> None:
for _ in range(instances):
worker(*args)
print("Serial Execution, CPU bound")
with timer():
serial_scheduler(8, cpu_worker, [10_000_000, 49])
print("Serial Execution, I/O bound")
with timer():
serial_scheduler(8, io_worker, [3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment