الدرس 1.2 · الكود والأرقام⏱ 12 دقيقة
الفصل 1: Threads و Processes و الـ GIL
تجربة: threads ضد processes
نفس الشغل بـ 3 طرق، على جهاز فيه 2 cores.
- Threads للحساب: 0.69 ثانية (أبطأ من 0.66).
- Processes: 0.35: أسرع 1.9 مرة.
- 20 انتظار: من 4 ثواني لـ 0.2 بالـ threads.
الشرح بالتفصيل
Python🖥 بيشتغل في برنامج روبو لاب على الكمبيوتر · النتيجة من الكتاب
import time, math
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def cpu_work(n): # حساب تقيل: مجموع جذور
return sum(math.sqrt(i) for i in range(n))
def io_work(_): # بيستنى (شبكة أو database)
time.sleep(0.2)
def timed(label, fn):
t = time.perf_counter(); fn(); print(f"{label:34} {time.perf_counter() - t:6.2f} s")
N = 3_000_000
timed("CPU x4 sequential", lambda: [cpu_work(N) for _ in range(4)])
with ThreadPoolExecutor(4) as ex: timed("CPU x4 threads (GIL)", lambda: list(ex.map(cpu_work, [N] * 4)))
with ProcessPoolExecutor(2) as ex: timed("CPU x4 processes (2 cores)", lambda: list(ex.map(cpu_work, [N] * 4)))
timed("IO x20 sequential", lambda: [io_work(0) for _ in range(20)])
with ThreadPoolExecutor(20) as ex: timed("IO x20 threads", lambda: list(ex.map(io_work, range(20))))
النتيجة:
CPU x4 sequential 0.66 s CPU x4 threads (GIL) 0.69 s CPU x4 processes (2 cores) 0.35 s IO x20 sequential 4.00 s IO x20 threads 0.20 s
الحساب بالـ threads: أبطأ شوية من التسلسل (تبديل القفل ليه تمن). الـ processes: 1.9 مرة أسرع على 2 cores (قريب من الحد). والانتظار بالـ threads: 20 مرة أسرع، لأن الـ 20 بيستنوا مع بعض. وده سبب إن سيرفر الويب (الجزء 11) بيخدم مئات الطلبات بـ threads أو async: أغلب وقت الطلب انتظار للـ database.
ملاحظةبايثون المتصفح مافيهاش threads ولا processes: دوس «🖥 شغّل على الجهاز» في برنامج روبو لاب.

