Thread load
examples/threads/thread_load.py
import threading import sys import time import random results = [] locker = threading.Lock() class ThreadedCount(threading.Thread): def __init__(self, n): threading.Thread.__init__(self) self.n = n def run(self): count = 0 total = 0 while count < 40000000 / self.n: rnd = random.random() total += rnd count += 1 locker.acquire() results.append({'count': count, 'total': total}) locker.release() return def main(): if len(sys.argv) != 2: exit("Usage: {} POOL_SIZE") size = int(sys.argv[1]) start = time.time() threads = [ ThreadedCount(n=size) for i in range(size) ] [ t.start() for t in threads ] [ t.join() for t in threads ] print("Results: {}".format(results)) totals = map(lambda r: r['total'], results) print("Total: {}".format(sum(totals))) end = time.time() print(end - start) if __name__ == '__main__': main()
$ time python thread_load.py 1
Results: [{'count': 40000000, 'total': 19996878.531261113}]
Total: 19996878.531261113
6.478948354721069
real 0m6.539s
user 0m6.491s
sys 0m0.012s
$ time python thread_load.py 4
Results: [{'count': 10000000, 'total': 5000680.7382364655}, {'count': 10000000, 'total': 5000496.15077697}, {'count': 10000000, 'total': 5000225.747780174}, {'count': 10000000, 'total': 4999503.803068357}]
Total: 20000906.43986197
6.180345296859741
real 0m6.241s
user 0m6.283s
sys 0m0.029s