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

// Function to be benchmarked
void sortVector(std::vector<int>& vec) {
    std::sort(vec.begin(), vec.end());
}

int main() {
    const int NUM_RUNS = 100;
    const int VECTOR_SIZE = 10000;

    std::vector<int> vec(VECTOR_SIZE);

    // Measure total time for multiple runs
    auto start = std::chrono::high_resolution_clock::now();

    for (int i = 0; i < NUM_RUNS; ++i) {
        // Reset vector for each run
        for (int j = 0; j < VECTOR_SIZE; ++j) {
            vec[j] = rand() % VECTOR_SIZE;
        }

        sortVector(vec);
    }

    auto end = std::chrono::high_resolution_clock::now();

    // Calculate average time
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    double averageTime = duration.count() / static_cast<double>(NUM_RUNS);

    std::cout << "Average time to sort " << VECTOR_SIZE << " integers: " 
              << averageTime << " microseconds" << std::endl;

    return 0;
}
Back to benchmarking