1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #include <vector>
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <chrono>
using namespace std;
int main(int argc, char* argv[])
{
const int size = 10000000;
vector<double> v1(size), v2(size);
const int max = 5;
auto f = [max]{ return rand() % max; };
srand(time(nullptr));
generate(begin(v1), end(v1), f);
generate(begin(v2), end(v2), f);
double scalar_product = 0;
auto it = begin(v2);
auto t1 = chrono::high_resolution_clock::now();
for_each(begin(v1), end(v1), [&scalar_product, &it](double e){ scalar_product += e * (*it); ++it; });
auto t2 = chrono::high_resolution_clock::now();
cout << "scalar_product = " << scalar_product << " duration = " << chrono::duration_cast<chrono::milliseconds>(t2 - t1).count() << endl;
return 0;
} |