为什么迭代器比vector <char>的operator []慢?

时间:2017-05-25 05:14:50

标签: c++11 vector iterator

对于我正在进行的项目,表现非常高尚。看看我做过的以下实验,

int main(int argc, char * argv[])
{
    size_t v_size = 10000000; // vector size
    vector<char> v(v_size);
    vector<char> buff(v_size);

    string cmd = argv[1];
    size_t n = std::stoll(argv[2]);

    if(cmd == "idx")
    {
        for(size_t i=0; i!=n; ++i)
        {
            for(size_t j=0; j!=v.size(); ++j)
            {
                buff[j] = v[j];
            }
        }
    }
    else if(cmd == "pp_itr")
    {
        for(size_t i=0; i!=n; ++i)
        {
            auto v_itr = v.begin();
            auto buff_itr = buff.begin();
            while(v_itr != v.end())
            {
                *buff_itr = *v_itr;
                ++v_itr;
                ++buff_itr;
            }
        }
    }
    else if(cmd == "itr_pp")
    {
        for(size_t i=0; i!=n; ++i)
        {
            auto v_itr = v.begin();
            auto buff_itr = buff.begin();
            while(v_itr != v.end())
            {
                *buff_itr = *v_itr;
                v_itr++;
                buff_itr++;
            }
        }
    }
    else
    {
        std::cout << "unknown command" << std::endl;
    }
}




Here is the result          
$ time ./a.out idx 500        // scan vector by operator[]
real    0m46.924s
user    0m46.883s
sys     0m0.013s

$ time ./a.out pp_itr 500     // scan vector by iterator ++iter
real    1m51.675s
user    1m51.587s
sys     0m0.023s

$ time ./a.out itr_pp 500     // scan vector by itertor itr++
real    2m52.314s
user    2m52.192s
sys     0m0.019s

++ itr比它更快的事实并不让我感到惊讶,正如许多人所说的那样。 我对运算符[]比迭代器快得多的结果感到非常惊讶。

0 个答案:

没有答案