Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...