vector()vs vector(0)无法解释的运行时差异

时间:2017-02-01 18:40:14

标签: c++ vector stl

版本1( 1572.38ms ):

#include <iostream>
#include <vector>
#include <chrono>

int main(int argc, char* argv[])
{
    std::chrono::time_point<std::chrono::steady_clock> startTime = std::chrono::steady_clock::now();
    int n = 1000000;
    int m = 1000;

    for (int k = 0; k < m; k++)
    {

        std::vector<int> array(0);

        array.reserve(n);

        for (int i = 0; i < n - 10; i++)
        {
            array.push_back(i);
        }
    }

    auto time = std::chrono::steady_clock::now() - startTime;
    std::cout   << "Elapsed time: "
            << std::chrono::duration<double, std::milli>(time).count()
            << " ms\n";
    return 0;
}

版本2( 3736.49ms ):

#include <iostream>
#include <vector>
#include <chrono>

int main(int argc, char* argv[])
{
    std::chrono::time_point<std::chrono::steady_clock> startTime = std::chrono::steady_clock::now();
    int n = 1000000;
    int m = 1000;

    for (int k = 0; k < m; k++)
    {

        std::vector<int> array;

        array.reserve(n);

        for (int i = 0; i < n - 10; i++)
        {
            array.push_back(i);
        }
    }

    auto time = std::chrono::steady_clock::now() - startTime;
    std::cout   << "Elapsed time: "
            << std::chrono::duration<double, std::milli>(time).count()
            << " ms\n";
    return 0;
}

有人可以向我解释为什么运行时间有这么大的差异?唯一的区别在于矢量构造。两者都是使用size = capacity = 0创建的。

编译器:g ++ 5.4.0 编译器标志:-Wall -std = c ++ 14 -O2

0 个答案:

没有答案