C++ STL vector 性能之push_back、emplace_back、reserve

#include <iostream>
#include <vector>
#include <chrono>
using namespace std;

constexpr int N = 10;

void timeMeasure(void(*f)()){
    auto begin = std::chrono::high_resolution_clock::now();
    uint32_t iterations = 10000;
    for(uint32_t i = 0; i < iterations; ++i)
    {
        f();
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end-begin).count();
    std::cout << duration << "ms total, average : " << duration * 1.0 / iterations << "ms." << std::endl;
}



void testPushBack(){
    vector<int> arr;
    for(int i = 0; i < N; i++){
        arr.push_back(i);
    }
}

void testEmplaceBack(){
    vector<int> arr;
    for(int i = 0; i < N; i++){
        arr.emplace_back(i);
    }
}

void testReserveWithPush(){
    vector<int> arr;
    arr.reserve(N);
    for(int i = 0; i < N; i++){
        arr.push_back(i);
    }
}

void testReserveWithEmplace(){
    vector<int> arr;
    arr.reserve(N);
    for(int i = 0; i < N; i++){
        arr.emplace_back(i);
    }
}


void testInitAndAssign(){
    vector<int> arr(N);
    for(int i = 0; i < N; i++){
        arr[i] = i;
    }
}

int main(){
    timeMeasure(testPushBack);
    timeMeasure(testEmplaceBack);
    timeMeasure(testReserveWithPush);
    timeMeasure(testReserveWithEmplace);
    timeMeasure(testInitAndAssign);
    return 0;
}

21ms total, average : 0.0021ms.
11ms total, average : 0.0011ms.
2ms total, average : 0.0002ms.
2ms total, average : 0.0002ms.
2ms total, average : 0.0002ms.

posted on 2023-04-10 15:15  七昂的技术之旅  阅读(102)  评论(0编辑  收藏  举报

导航