Advertisement
cd62131

Accumulate and For

Mar 7th, 2014
333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <array>
  2. #include <chrono>
  3. #include <iostream>
  4. #include <numeric>
  5. #include <random>
  6. #include <vector>
  7. using namespace std;
  8. using chrono::system_clock;
  9. using chrono::high_resolution_clock;
  10. using chrono::duration_cast;
  11. using chrono::microseconds;
  12. int main() {
  13.   vector<int> v;
  14.   unsigned seed = system_clock::now().time_since_epoch().count();
  15.   mt19937_64 gen(seed);
  16.   uniform_int_distribution<int> dist(0, 9);
  17.   for (int i = 0; i < 300000; i++) v.push_back(dist(gen));
  18.   auto t0 = high_resolution_clock::now();
  19.   long acc = accumulate(v.begin(), v.end(), 0); cout << "acc(vec): " << acc << ", ";
  20.   auto t1 = high_resolution_clock::now();
  21.   cout << duration_cast<microseconds>(t1 - t0).count() << " ms" << endl;
  22.   t0 = high_resolution_clock::now();
  23.   acc = 0; for (auto& e: v) acc += e; cout << "for(vec): " << acc << ", ";
  24.   t1 = high_resolution_clock::now();
  25.   cout << duration_cast<microseconds>(t1 - t0).count() << " ms" << endl;
  26.   array<int, 300000> a;
  27.   for (auto& e: a) e = dist(gen);
  28.   t0 = high_resolution_clock::now();
  29.   acc = accumulate(a.begin(), a.end(), 0); cout << "acc(arr): " << acc << ", ";
  30.   t1 = high_resolution_clock::now();
  31.   cout << duration_cast<microseconds>(t1 - t0).count() << " ms" << endl;
  32.   t0 = high_resolution_clock::now();
  33.   acc = 0; for (auto& e: a) acc += e; cout << "for(arr): " << acc << ", ";
  34.   t1 = high_resolution_clock::now();
  35.   cout << duration_cast<microseconds>(t1 - t0).count() << " ms" << endl;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement