gcc可以使我的代码并行吗? [英] Can gcc make my code parallel?

查看:281
本文介绍了gcc可以使我的代码并行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道gcc中是否有优化,可以使某些单线程代码(如下面的示例)并行执行.如果没有,为什么?如果可以,什么样的优化是可能的?

I was wondering if there is an optimization in gcc that can make some single-threaded code like the example below execute in parallel. If no, why? If yes, what kind of optimizations are possible?

#include <iostream>

int main(int argc, char *argv[])
{
    int array[10];
    for(int i = 0; i < 10; ++ i){
        array[i] = 0;
    }
    for(int i = 0; i < 10; ++ i){
        array[i] += 2;
    }
    return 0;
}

已添加:

感谢OpenMP链接,尽管我认为它很有用,但我的问题与编译相同代码而无需重写smth有关. 所以基本上我想知道是否:

Thanks for OpenMP links, and as much as I think it's useful, my question is related to compiling same code without the need to rewrite smth. So basically I want to know if:

  1. 使代码并行(至少在某些情况下)而无需重写是可能的吗?
  2. 如果是,可以处理哪些案件?如果没有,为什么?

推荐答案

编译器可以尝试自动并行化您的代码,但不会通过创建线程来实现.它可能会使用矢量化指令(例如,针对Intel CPU的 intel内在函数)来在一个处理器上对多个元素进行操作.时间,它可以检测到可以使用这些指令(例如,当您在正确对齐的数据结构的连续元素上多次执行相同的操作时).您可以通过告诉编译器您的CPU支持哪个内部指令集(例如-mavx, -msse4.2 ...)来帮助编译器.

The compiler can try to automatically parallelise your code, but it wont do it by creating threads. It may use vectorised instructions (intel intrinsics for an intel CPU, for example) to operate on multiple elements at a time, where it can detect that using those instructions is possible (for example when you perform the same operation multiple times on consecutive elements of a correctly aligned data structure). You can help the compiler by telling it which intrinsic instruction set your CPU supports (-mavx, -msse4.2 ... for example).

您也可以直接使用这些指令,但是对于程序员而言,这需要大量的工作.还有一些库已经在执行此操作(请参见 Agner Fog的博客中的矢量类).

You can also use these instructions directly, but it requires a non-trivial amount of work for the programmer. There are also libraries which do this already (see the vector class here Agner Fog's blog).

通过使用OpenMP( OpenMP介绍),您可以使编译器使用多个线程进行自动并行化,比编译器自身自动并行化更能指示编译器自动并行化.

You can get the compiler to auto-parallelise using multiple threads by using OpenMP (OpenMP introducion), which is more instructing the compiler to auto-parallelise, than the compiler auto-parallelising by itself.

这篇关于gcc可以使我的代码并行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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