example4_comparative_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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
#include <random>
#include <functional>

// Timing function
template<typename Func>
long long measureTime(Func func) {
    auto start = std::chrono::high_resolution_clock::now();
    func();
    auto end = std::chrono::high_resolution_clock::now();
    return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
}

// Sorting algorithms to compare
void bubbleSort(std::vector<int>& vec) {
    for (size_t i = 0; i < vec.size(); ++i)
        for (size_t j = 0; j < vec.size() - 1; ++j)
            if (vec[j] > vec[j + 1])
                std::swap(vec[j], vec[j + 1]);
}

void quickSort(std::vector<int>& vec) {
    std::sort(vec.begin(), vec.end());
}

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

    std::vector<int> original(VECTOR_SIZE);
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, VECTOR_SIZE);

    // Initialize vector with random numbers
    for (int& num : original) {
        num = dis(gen);
    }

    // Benchmark bubble sort
    long long bubbleSortTime = 0;
    for (int i = 0; i < NUM_RUNS; ++i) {
        std::vector<int> vec = original;
        bubbleSortTime += measureTime([&]() { bubbleSort(vec); });
    }

    // Benchmark quick sort
    long long quickSortTime = 0;
    for (int i = 0; i < NUM_RUNS; ++i) {
        std::vector<int> vec = original;
        quickSortTime += measureTime([&]() { quickSort(vec); });
    }

    std::cout << "Average Bubble Sort time: " << bubbleSortTime / NUM_RUNS << " microseconds" << std::endl;
    std::cout << "Average Quick Sort time: " << quickSortTime / NUM_RUNS << " microseconds" << std::endl;

    return 0;
}
Back to benchmarking