使用g ++ -std = c ++ 0x的代码运行速度较慢 [英] Code running slower with g++ -std=c++0x

查看:92
本文介绍了使用g ++ -std = c ++ 0x的代码运行速度较慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测试 std :: swap vector :: swap 和我在有和没有 -std = c ++ 0x 选项的情况下进行编译。我已经注意到大约200毫秒的差异,当我不包含此选项时程序运行得更快。

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

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

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)

不使用-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

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


推荐答案

好吧,我们不知道您使用的G ++版本,也不知道在编译时指定的标志。

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

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

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.

这篇关于使用g ++ -std = c ++ 0x的代码运行速度较慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆