example2_simple_benchmarking.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
#include <iostream>
#include <chrono>
#include <vector>
#include <algorithm>

template<typename Func>
double benchmark(Func f, int iterations = 1000000) {
    auto start = std::chrono::high_resolution_clock::now();
    
    for (int i = 0; i < iterations; ++i) {
        f();
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;
    
    return diff.count() / iterations;
}

int main() {
    std::vector<int> v(10000);
    std::generate(v.begin(), v.end(), std::rand);

    double time = benchmark([&v]() {
        std::sort(v.begin(), v.end());
    }, 100);  // Run 100 iterations

    std::cout << "Average time to sort 10000 elements: " << time << " seconds" << std::endl;

    return 0;
}
Back to timers