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

int main() {
    const int NUM_ELEMENTS = 1000000;
    std::vector<int> vec;

    // Reserve space to avoid reallocations
    vec.reserve(NUM_ELEMENTS);

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

    for (int i = 0; i < NUM_ELEMENTS; ++i) {
        vec.push_back(i);
    }

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;

    std::cout << "Time to add " << NUM_ELEMENTS << " elements: " 
              << diff.count() << " seconds" << std::endl;
    std::cout << "Final vector size: " << vec.size() << std::endl;

    return 0;
}
Back to push_back