Skip to content

Instantly share code, notes, and snippets.

@alonsoir
Created January 22, 2025 10:43
Show Gist options
  • Save alonsoir/40fcd1c884ce074192dd081c30b53e9b to your computer and use it in GitHub Desktop.
Save alonsoir/40fcd1c884ce074192dd081c30b53e9b to your computer and use it in GitHub Desktop.
Para tareas multicore, es mejor usar Pool que Parallel
from multiprocessing import Pool
from joblib import Parallel, delayed
import time
def medir_tiempo(func):
def wrapper(*args, **kwargs):
inicio = time.time()
resultado = func(*args, **kwargs)
fin = time.time()
print(f"{func.__name__} ejecutada en: {fin - inicio:.5f} segundos")
return resultado
return wrapper
def process_item(item):
# Some CPU-bound operation
return item**2
@medir_tiempo
def heavy():
data = range(1_000_000)
results = Parallel(n_jobs=16)(
delayed(process_item)(item) for item in data
)
@medir_tiempo
def heavy2():
data = range(1_000_000)
with Pool(processes=16) as pool: # Use 16 CPU cores
results = pool.map(process_item, data)
if __name__ == "__main__":
heavy()
heavy2()

/Users/aironman/Library/Caches/pypoetry/virtualenvs/attendance-system-SYPtwedO-py3.10/bin/python3.10 -X pycache_prefix=/Users/aironman/Library/Caches/JetBrains/PyCharmCE2024.2/cpython-cache /Users/aironman/Applications/PyCharm Community.app/Contents/plugins/python-ce/helpers/pydev/pydevd.py --multiprocess --qt-support=auto --client 127.0.0.1 --port 54163 --file /Users/aironman/git/attendance_system/multiprocess.py Connected to pydev debugger (build 242.23339.19) heavy ejecutada en: 14.77763 segundos heavy2 ejecutada en: 1.50778 segundos

Process finished with exit code 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment