Created
July 10, 2024 09:48
-
-
Save tomasruizt/4aaf2e4787d7f9c66632500c28c8a0f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import multiprocessing | |
import time | |
inputs = ["a", "b", "c", "d"] | |
def slow_func(x: str) -> str: | |
print(f"converting {x} to {x + x}...") | |
time.sleep(1) | |
return x + x | |
print("starting slow sequential loop") | |
start = time.time() | |
results = [] | |
for i in inputs: | |
results.append(slow_func(i)) | |
print("done. results:", results) | |
print(f"time taken: {time.time() - start:.2f}s") | |
print() | |
print("starting fast parallel loop") | |
start = time.time() | |
with multiprocessing.Pool(processes=4) as pool: | |
results = pool.map(slow_func, inputs) | |
print("done. results:", results) | |
print(f"time taken: {time.time() - start:.2f}s") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: