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

发布时间 2023-04-10 15:24:13作者: 偷不走的影子
#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::nanoseconds>(end-begin).count();
    std::cout << duration << "ns total, average : " << duration / iterations << "ns." << 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);
    }
}

int main(){
    timeMeasure(testPushBack);
    timeMeasure(testEmplaceBack);
    timeMeasure(testReserveWithPush);
    timeMeasure(testReserveWithEmplace);
    return 0;
}
24586939ns total, average : 2458ns.
12163285ns total, average : 1216ns.
2821536ns total, average : 282ns.
2851876ns total, average : 285ns.