الدرس 8.2 · الكود والأرقام⏱ 12 دقيقة
الفصل 8: MapReduce: ابعت الحساب للبيانات
تجربة: 4.8 مليون كلمة
عدّ الكلمات بـ 1 و 2 و 4 workers.
- من 1 لـ 2: أسرع 1.9 مرة.
- من 2 لـ 4: أبطأ: الجهاز فيه 2 cores بس.
- ونفس النتيجة بالظبط في التلاتة.
الشرح بالتفصيل
Python🖥 بيشتغل في برنامج روبو لاب على الكمبيوتر · النتيجة من الكتاب
import time
from collections import Counter
from multiprocessing import Pool
def map_chunk(lines): # Map: كل worker بيعدّ في حتته
return Counter(w for line in lines for w in line.split())
def reduce_counts(counters): # Reduce: اجمع النتايج
total = Counter()
for c in counters: total.update(c)
return total
lines = open("corpus.txt").read().splitlines() # 400,000 سطر (29 MB)
for workers in (1, 2, 4):
t = time.perf_counter()
chunks = [lines[i::workers * 4] for i in range(workers * 4)]
with Pool(workers) as pool:
result = reduce_counts(pool.map(map_chunk, chunks))
print(f"{workers} workers: {time.perf_counter() - t:.2f} s top: {result.most_common(2)} total words {sum(result.values()):,}")
النتيجة:
1 workers: 0.89 s top: [('class', 400442), ('robot', 400372)] total words 4,800,000
2 workers: 0.47 s top: [('class', 400442), ('robot', 400372)] total words 4,800,000
4 workers: 0.58 s top: [('class', 400442), ('robot', 400372)] total words 4,800,000الجهاز ده فيه 2 cores بس. من worker لـ 2: أسرع 1.9 مرة (قريب من المثالي 2). من 2 لـ 4: أبطأ، لأن مفيش cores زيادة، والـ workers الزيادة بتتزاحم، وتمن نقل البيانات بين الـ processes (pickle للـ lists و الـ Counters) زاد. ونفس النتيجة بالظبط في التلاتة. ده Amdahl (الجزء 6) و«الأجهزة مش ببلاش» في نفس التجربة.
ملاحظةmultiprocessing مش موجود في بايثون المتصفح: دوس «🖥 شغّل على الجهاز» في برنامج روبو لاب. والكود بيعمل corpus.txt لوحده الأول. والأرقام على حسب عدد الـ cores عندك.

