fork download
  1. #include <algorithm>
  2. #include <ctime>
  3. #include <iostream>
  4. #include <iterator>
  5. #include <vector>
  6.  
  7. using namespace std;
  8.  
  9. vector<int> createArrays() {
  10. vector<int> result(rand() % 13);
  11.  
  12. generate(result.begin(), result.end(), rand);
  13.  
  14. return result;
  15. }
  16.  
  17. vector<int> test1(const vector<int>& testValues1, const vector<int>& testValues2) {
  18. vector<int> result(testValues1.size() * testValues2.size());
  19. unsigned sz2 = testValues2.size();
  20. const int *tv1 = testValues1.data();
  21. const int *tv2 = testValues2.data();
  22.  
  23. for_each(begin(result), end(result), [&, it = 0U](auto& i) mutable {
  24. i = tv1[it / sz2] + tv2[it % sz2];
  25. ++it;
  26. });
  27.  
  28. return result;
  29. }
  30.  
  31. vector<int> test2(const vector<int>& testValues1, const vector<int>& testValues2) {
  32. vector<int> result(testValues1.size() * testValues2.size());
  33. auto i = begin(result);
  34.  
  35. std::for_each(cbegin(testValues1), cend(testValues1), [&](const auto& A) { std::for_each(cbegin(testValues2), cend(testValues2), [&](const auto& B) { *i++ = A + B; }); });
  36. return result;
  37. }
  38.  
  39.  
  40. int main() {
  41. clock_t start;
  42. clock_t total1 = 0;
  43. clock_t total2 = 0;
  44. auto first = &test1;
  45. auto second = &test2;
  46.  
  47. srand(static_cast<unsigned int>(time(nullptr)));
  48.  
  49. for (auto i = 0; i < 100; ++i) {
  50. auto testValues1 = createArrays();
  51. auto testValues2 = createArrays();
  52.  
  53. start = clock();
  54. const auto result1 = first(testValues1, testValues2);
  55. total1 += clock() - start;
  56.  
  57. start = clock();
  58. const auto result2 = second(testValues1, testValues2);
  59. total2 += clock() - start;
  60.  
  61. if (!equal(cbegin(result1), cend(result1), cbegin(result2), cend(result2))) {
  62. cout << "MISMATCH\n";
  63. break;
  64. }
  65.  
  66. swap(total1, total2);
  67. swap(first, second);
  68. }
  69. cout << "Test1: " << total1 << endl << "Test2: " << total2 << endl;
  70. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Test1: 195
Test2: 127