example3_comparing_implementations.cpp

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <chrono>
#include <vector>
#include <algorithm>
#include <numeric>

template<typename Func>
double measure_time(Func f) {
    auto start = std::chrono::high_resolution_clock::now();
    f();
    auto end = std::chrono::high_resolution_clock::now();
    return std::chrono::duration<double, std::milli>(end - start).count();
}

int sum_for_loop(const std::vector<int>& v) {
    int sum = 0;
    for (int i = 0; i < v.size(); ++i) {
        sum += v[i];
    }
    return sum;
}

int sum_range_based(const std::vector<int>& v) {
    int sum = 0;
    for (int num : v) {
        sum += num;
    }
    return sum;
}

int sum_std_accumulate(const std::vector<int>& v) {
    return std::accumulate(v.begin(), v.end(), 0);
}

int main() {
    std::vector<int> numbers(10000000);
    std::iota(numbers.begin(), numbers.end(), 1);  // Fill with 1 to 10000000

    std::cout << "For loop: " << measure_time([&]() { sum_for_loop(numbers); }) << " ms\n";
    std::cout << "Range-based for loop: " << measure_time([&]() { sum_range_based(numbers); }) << " ms\n";
    std::cout << "std::accumulate: " << measure_time([&]() { sum_std_accumulate(numbers); }) << " ms\n";

    return 0;
}
Back to timers