In [1]:
# Python 3.
from concurrent import futures
import datetime
import itertools
import time
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

WORKERS=5
ITERS=15

def test_multithreading(Executor, function):
    start_time = datetime.datetime.now()
    with Executor(max_workers=WORKERS) as ex:
        result = list(ex.map(function, itertools.repeat(start_time, ITERS)))

    start, stop = np.array(result).T
    return start, stop

def idle(start_time):
    elapsed = lambda: (datetime.datetime.now() - start_time).total_seconds()
    start = elapsed()
    time.sleep(2)
    stop = elapsed()
    return (start, stop)

def busy(start_time):
    elapsed = lambda: (datetime.datetime.now() - start_time).total_seconds()
    start = elapsed()
    sum(range(10**7))
    stop = elapsed()
    return (start, stop)

def plot(start, stop, title):
    elapsed = stop - start
    plt.barh(range(len(start)), elapsed, left=start)
    plt.ylabel("Task number")
    plt.xlabel("Seconds")
    plt.grid(axis='x')
    plt.title(title)
    plt.gca().invert_yaxis()
    plt.savefig("/Users/grigg/Desktop/{}.svg".format(title.replace(" ", "-")))
In [2]:
plot(*test_multithreading(futures.ThreadPoolExecutor, busy), title="busy threads")
In [3]:
plot(*test_multithreading(futures.ThreadPoolExecutor, idle), title="idle threads")
In [4]:
plot(*test_multithreading(futures.ProcessPoolExecutor, idle), title="idle processes")
In [5]:
plot(*test_multithreading(futures.ProcessPoolExecutor, busy), title="busy processes")