使用g ++ -std = c ++ 0x,代码运行速度较慢

0xF*_*xFF -1 c++ performance g++ c++11

我试图测试中的性能差异std::swap,并vector::swap和我有和没有编译-std=c++0x选项.我注意到大约200毫秒的差异,当我不包括这个选项时程序运行得更快.

#include <iostream>
#include <string>
#include <vector>

int main()
{
    commentator.setReportStream (cout);

    size_t nbElts = 2048;
    vector<int> v, w;

    v.resize (nbElts);
    w.reserve (nbElts);

    for (int i = 0; i < nbElts; ++i) {
        w.push_back (i);
    }

    commentator.start ("std::swap", __FUNCTION__);
    for (int i = 0; i < 10000000; ++i) {
        std::swap (v, w);
    }
    commentator.stop (MSG_DONE);

    commentator.start ("vector::swap", __FUNCTION__);
    for (int i = 0; i < 10000000; ++i) {
        v.swap (w);
    }
    commentator.stop (MSG_DONE);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

commentator对象显示运行时间.为什么运行时间不同? gcc版本4.6.3 20120306(Red Hat 4.6.3-2)(GCC)

没有-std = c ++ 0x的运行时间

std::swap...done (0.319952 s)
Completed activity: std::swap (r: 0.3214s, u: 0.32s, s: 0s) done

vector::swap...done (0.26396 s)
Completed activity: vector::swap (r: 0.2652s, u: 0.264s, s: 0s) done
Run Code Online (Sandbox Code Playgroud)

使用-std = c ++ 0x

std::swap...done (0.548917 s)
Completed activity: std::swap (r: 0.5507s, u: 0.5489s, s: 0s) done

vector::swap...done (0.508922 s)
Completed activity: vector::swap (r: 0.5105s, u: 0.5089s, s: 0s) done
Run Code Online (Sandbox Code Playgroud)

jal*_*alf 8

好吧,我们不知道你正在使用哪个版本的G ++,我们不知道你在编译时指定了哪些标志.

但是如果需要你的代码半秒来做几百万个指针交换(在C++ 0x中交换向量),那么我认为你可以很自然地编译你没有启用优化.如果您在没有优化的情况下对代码进行基准测试,那么您将获得无用的数据,并且您在浪费时间.如果您关心代码的速度,请告诉编译器生成快速代码,然后测量差异.