Code running slower with g++ -std=c++0x

送分小仙女□ 提交于 2019-12-13 08:39:41

问题


I was trying to test the difference in the performance of std::swap and vector::swap and I compiled with and without the -std=c++0x option. I have noticed about ~200ms of difference, with the program running faster when I do not include this option.

#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;
}

The commentator object shows the running time. Why is the difference in running time? gcc version 4.6.3 20120306 (Red Hat 4.6.3-2) (GCC)

Runing time without -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

with -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

回答1:


Well, we don't know which version of G++ you're using, and we don't know what flags you specify when compiling.

But if it takes your code half a second to do a few million pointer swaps (swapping vectors in C++0x), then I think it's pretty safe to say that you're compiling without optimizations enabled. If you're benchmarking code without optimization, you get useless data, and you are wasting your time. If you care about the speed of your code, tell your compiler to generate fast code, and then measure the differences.



来源:https://stackoverflow.com/questions/10436640/code-running-slower-with-g-std-c0x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!