Calculating the Sum of a Vector
What is the fastest way to add the elements of a std::vector
? To get the answer, I fill a std::vector
with one hundred million arbitrary but uniformly distributed numbers between 1 and 10. The task is to calculate the sum of the numbers in various ways. I use the performance of a single threaded addition as the reference execution time. I discuss atomics, locks, thread-local data and tasks.
Let’s start with the single threaded scenario.
Single Threaded addition of a Vector
The straightforward strategy is it to add the numbers in a range-based for loop.
Range-based for Loop
The summation takes place in line 27.
1
// calculateWithLoop.cpp
2
3
#include
<chrono>
4
#include
<iostream>
5
#include
<random>
6
#include
<vector>
7
8
constexpr
long
long
size
=
100000000
;
9
10
int
main
(){
11
12
std
::
cout
<<
std
::
endl
;
13
14
std
::
vector
<
int
>
randValues...