Measuring CPU performance with a parallelized vector sum

The example compares the time spend in computing the sum of all coefficients of a matrix when the function walks through the coefficients by rows or by columns when the computation is parallelized.

Vector Sum

from tqdm import tqdm
import numpy
import matplotlib.pyplot as plt
from pandas import DataFrame
from teachcompute.ext_test_case import measure_time, unit_test_going
from teachcompute.validation.cpu._validation import (
    vector_sum_array as vector_sum,
    vector_sum_array_parallel as vector_sum_parallel,
)

obs = []
dims = [500, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 2000]
if unit_test_going():
    dims = [10, 20]
for dim in tqdm(dims):
    values = numpy.ones((dim, dim), dtype=numpy.float32).ravel()
    diff = abs(vector_sum(dim, values, True) - dim**2)

    res = measure_time(lambda: vector_sum(dim, values, True), max_time=0.5)

    obs.append(
        dict(
            dim=dim,
            size=values.size,
            time=res["average"],
            direction="rows",
            time_per_element=res["average"] / dim**2,
            diff=diff,
        )
    )

    res = measure_time(lambda: vector_sum_parallel(dim, values, True), max_time=0.5)

    obs.append(
        dict(
            dim=dim,
            size=values.size,
            time=res["average"],
            direction="rows//",
            time_per_element=res["average"] / dim**2,
            diff=diff,
        )
    )

    diff = abs(vector_sum(dim, values, False) - dim**2)
    res = measure_time(lambda: vector_sum_parallel(dim, values, False), max_time=0.5)

    obs.append(
        dict(
            dim=dim,
            size=values.size,
            time=res["average"],
            direction="cols//",
            time_per_element=res["average"] / dim**2,
            diff=diff,
        )
    )


df = DataFrame(obs)
piv = df.pivot(index="dim", columns="direction", values="time_per_element")
print(piv)
  0%|          | 0/14 [00:00<?, ?it/s]
  7%|▋         | 1/14 [00:06<01:23,  6.43s/it]
 14%|█▍        | 2/14 [00:11<01:08,  5.67s/it]
 21%|██▏       | 3/14 [00:15<00:54,  4.97s/it]
 29%|██▊       | 4/14 [00:18<00:42,  4.21s/it]
 36%|███▌      | 5/14 [00:20<00:29,  3.32s/it]
 43%|████▎     | 6/14 [00:23<00:25,  3.15s/it]
 50%|█████     | 7/14 [00:25<00:19,  2.81s/it]
 57%|█████▋    | 8/14 [00:27<00:14,  2.45s/it]
 64%|██████▍   | 9/14 [00:28<00:11,  2.21s/it]
 71%|███████▏  | 10/14 [00:30<00:08,  2.18s/it]
 79%|███████▊  | 11/14 [00:32<00:06,  2.13s/it]
 86%|████████▌ | 12/14 [00:34<00:04,  2.03s/it]
 93%|█████████▎| 13/14 [00:36<00:01,  1.97s/it]
100%|██████████| 14/14 [00:38<00:00,  1.90s/it]
100%|██████████| 14/14 [00:38<00:00,  2.74s/it]
direction        cols//          rows        rows//
dim
500        1.072867e-08  2.317543e-09  1.079809e-08
700        5.984602e-09  1.196886e-09  5.927380e-09
800        4.683267e-09  1.221538e-09  4.340294e-09
900        3.889213e-09  1.494314e-09  3.683368e-09
1000       3.667275e-09  1.558552e-09  3.167424e-09
1100       3.650802e-09  1.432739e-09  2.968966e-09
1200       3.353628e-09  1.464854e-09  2.266978e-09
1300       3.360654e-09  1.482433e-09  1.779446e-09
1400       3.235819e-09  1.541875e-09  1.625567e-09
1500       3.098604e-09  1.505656e-09  1.474872e-09
1600       3.468438e-09  1.592590e-09  1.480811e-09
1700       3.216257e-09  1.370334e-09  1.524832e-09
1800       3.430561e-09  1.431448e-09  1.383657e-09
2000       3.611785e-09  1.496696e-09  1.074231e-09

Plots

piv_diff = df.pivot(index="dim", columns="direction", values="diff")
piv_time = df.pivot(index="dim", columns="direction", values="time")

fig, ax = plt.subplots(1, 3, figsize=(12, 6))
piv.plot(ax=ax[0], logx=True, title="Comparison between two summation")
piv_diff.plot(ax=ax[1], logx=True, logy=True, title="Summation errors")
piv_time.plot(ax=ax[2], logx=True, logy=True, title="Total time")
fig.tight_layout()
fig.savefig("plot_bench_cpu_vector_sum_parallel.png")
Comparison between two summation, Summation errors, Total time
/home/xadupre/.local/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py:822: UserWarning: Data has no positive values, and therefore cannot be log-scaled.
  labels = axis.get_majorticklabels() + axis.get_minorticklabels()

The summation by rows is much faster as expected. That explains why it is usually more efficient to transpose the first matrix before a matrix multiplication. Parallelization is faster.

Total running time of the script: (0 minutes 39.811 seconds)

Gallery generated by Sphinx-Gallery