example3_performance_considerations.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
#include <cassert>
#include <iostream>
#include <chrono>
#include <vector>
#include <stdexcept>

void performOperationWithAssert(const std::vector<int>& vec, int index) {
    assert(index < vec.size() && "Index out of bounds");
    std::cout << vec[index] << std::endl;
}

void performOperationWithException(const std::vector<int>& vec, int index) {
    if (index >= vec.size()) {
        throw std::out_of_range("Index out of bounds");
    }
    std::cout << vec[index] << std::endl;
}

int main() {
    std::vector<int> numbers(1000000, 42);
    const int iterations = 1000000;

    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < iterations; ++i) {
        performOperationWithAssert(numbers, i % numbers.size());
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> assertTime = end - start;

    start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < iterations; ++i) {
        try {
            performOperationWithException(numbers, i % numbers.size());
        } catch (const std::out_of_range&) {
            // Do nothing
        }
    }
    end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> exceptionTime = end - start;

    std::cout << "Time with assertions: " << assertTime.count() << " seconds" << std::endl;
    std::cout << "Time with exceptions: " << exceptionTime.count() << " seconds" << std::endl;

    return 0;
}
Back to exception_vs_assertion