dimanche 28 février 2016

emplace_back takes more time than push_back for a pre constructed object

I understand the reasons why emplace_back is preferred over push_back. I have the following piece of code:

#include <iostream>
#include <vector>
#include <ctime>
#include <ratio>
#include <chrono>

using namespace std;
using namespace std::chrono;

class X 
{
};

void get_timings()
{
    high_resolution_clock::time_point t, t1;
    duration<double> time_span;
    const std::uint64_t M = 999999999;
    std::vector<X> vec;
    vec.reserve(M);
    for (std::uint64_t i = 0; i < M; ++i)
    {
         vec.push_back(X());    
    }
    vec.clear();    
    vec.reserve(M);
    X x;    
    t = high_resolution_clock::now();
    for (std::uint64_t i = 0; i < M; ++i)
    {
         vec.push_back(x);    
    }
    t1 = high_resolution_clock::now();
    time_span = duration_cast<duration<double>>(t1 - t);

    // 1.
    std::cout << "Push back same object " << time_span.count() << std::endl;

    vec.clear();
    vec.reserve(M); 
    t = high_resolution_clock::now();
    for (std::uint64_t i = 0; i < M; ++i)
    {
        vec.emplace_back(x);    
    }
    t1 = high_resolution_clock::now();
    time_span = duration_cast<duration<double>>(t1 - t);

    // 2.
    std::cout << "Emplace back same object " << time_span.count() << std::endl; 
}

Following is the compilation line:

g++ testing_emplace.cpp   (No optimizations)

OS: CentOS7.2
8GB RAM
Compiler : gcc 4.9.2

I tried the experiments with different values of M. As the value of M increased the time difference between emplace and push back increased. As M increased emplace took more amount of time.

Is my experiment wrong ? Is emplace_back supposed to take the same time or less time as push_back always.

Aucun commentaire:

Enregistrer un commentaire