加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C 11与OpenMP一起提供了较慢的可执行文件

发布时间:2020-12-16 10:41:25 所属栏目:百科 来源:网络整理
导读:我正在尝试学习OpenMP,并希望使用OpenMP学习加速.为此,我写了以下小程序: #include vector#include cmathint main() { static const unsigned int testDataSize = 1 28; std::vectordouble a (testDataSize),b (testDataSize); for (int i = 0; i testDataS
我正在尝试学习OpenMP,并希望使用OpenMP学习加速.为此,我写了以下小程序:

#include <vector>
#include <cmath>

int main() {
    static const unsigned int testDataSize = 1 << 28;

    std::vector<double> a (testDataSize),b (testDataSize);

    for (int i = 0; i < testDataSize; ++i) {
        a [i] = static_cast<double> (23 ^ i) / 1000.0;
    }
    b.resize(testDataSize);

    #pragma omp parallel for
    for (int i = 0; i < testDataSize; ++i) {
        b [i] = std::pow(a[i],3) * std::exp(-a[i] * a[i]);
        b [i] += std::pow(a[i],5) * std::exp(-a[i] * a[i]);
        b [i] += std::pow(a[i],7) * std::exp(-a[i] * a[i]);
        b [i] += std::pow(a[i],9) * std::exp(-a[i] * a[i]);
        b [i] += std::pow(a[i],11) * std::exp(-a[i] * a[i]);
        b [i] += std::pow(a[i],13) * std::exp(-a[i] * a[i]);
        b [i] += std::pow(a[i],15) * std::exp(-a[i] * a[i]);
        b [i] += std::pow(a[i],17) * std::exp(-a[i] * a[i]);
        b [i] += std::pow(a[i],19) * std::exp(-a[i] * a[i]);
        b [i] += std::pow(a[i],21) * std::exp(-a[i] * a[i]);
    }

    return 0;
}

我使用或不使用-std = c 11指令编译了上面的代码.我注意到当我使用-std = c 11指令时,我的代码运行速度大约慢了8倍,因为没有使用它.我在Linux Debian系统上使用-O3和gcc版本4.9.2.此外,当我在不使用OpenMP的情况下比较执行时间时,我注意到速度差异.因此,在我看来,-std = c 11存在问题,而不是OpenMP存在问题.

详细地说,我获得了以下执行时间(使用Linux time命令测量)

使用OpenMP编译和-std = c 11:35.262s

仅使用OpenMP编译:5.875s

仅使用-std = c 11:2m12进行编译

没有OpenMP的编译和-std = c 11:23.757s

使用-std = c 11时执行时间慢得多的原因是什么?

非常感谢任何帮助或建议!

在我的拙见中,我已经标记了最好的答案.在oLen的回答的后续内容中,我已经制作了自己的pow(double,int)函数,如下所示:

double my_pow(double base,int exp) {
    double result = 1.0;

    while (exp) {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        base *= base;
    }

    return result;
}

我不确定这是否是计算某个基数的整数幂的最有效方法,但是在使用或不使用std = c 11进行编译时,使用此函数可以得到与计算效率完全相同的结果与oLen的完全一致回答.

解决方法

原因是没有-std = c 11的版本使用std :: pow(double,int),这显然在C 11中不可用,并且比std :: pow(double,double)更快.如果用双打(3.0,5.0等)替换整数(3,5等),您将获得相同的速度.

编辑:以下是g版4.8.4的时间安排:原始版本:-O3 -fopenmp:10.678秒-O3 -fopenmp -std = c 11:36.994 s在整数后添加“.0”:-O3 -fopenmp:36.679秒-O3 -fopenmp -std = c 11:36.938 s

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读