OpenMP基础使用

来源:互联网 发布:java 线程池 名字关闭 编辑:程序博客网 时间:2024/06/08 18:39
    OpenMP是CPU并行加速相关的编译处理方案,VS很早的版本就对其提供了支持,不过默认是关闭的。要开启这一支持,只需要在项目的属性中设置就可以,具体选项为:配置属性->C/C++->语言 在右侧列表中有一项“OpenMP 支持”,下拉选择“是(/openmp)”就可以了。 
    其实本人是在前几天才知道有这个东西存在的,朋友跟我说这个东西用起来相比正常的开启多线程要方便很多,经过研究发现其确有方便之处。好吧,下面还是写一下它该怎么用吧,这里只是写最基本的,当然后面用到相关的也会加上去。 

    在选择上面的选项之后,直接可以用“#pragma omp parallel for”标示给代码中的for循环加速,实例如下:

#include <stdio.h> #include <time.h>#include <stdlib.h>   void test()//纯粹浪费时间{    int add = 0;    for (int runtime = 0; runtime < 100000000; runtime++)        add++;    printf("%d\n", add);}void main(){    int beginClock = clock();//记录开始时间#pragma omp parallel for    for (int testtime = 0; testtime<8; testtime++)    {        test();//运行计算    }    printf("运行时间为:%dms\n", clock() - beginClock);//输出图像处理花费时间信息      system("pause");}
    在本人的四核八线程i7 CPU上,其运行消耗时间为261ms,如果删除掉“#pragma omp parallel for”,则运行花费时间为1816ms,相差接近七倍,而如果把main里面的循环次数改为9次,则花费时间变为477ms,可见其正的用上了CPU能支持的最多线程数(八条线程)进行了处理。 
    当然很多需要并行的代码用for写起来会比较痛苦,这时可以用“#pragma omp parallel sections”标示将要并行执行的代码括起来,然后用”#pragma omp section”标示每一条线程的执行代码,示例如下:

#include <stdio.h> #include <time.h>#include <stdlib.h>   void test(int time)//纯粹浪费时间{    int add = 0;    for (int runtime = 0; runtime < 100000000; runtime++)        add++;    printf("%d\n", time);}void main(){    int beginClock = clock();//记录开始时间    /*并行内容*/#pragma omp parallel sections    {        #pragma omp section        {            test(1);        }        #pragma omp section        {            test(2);        }        #pragma omp section        {            test(3);        }        #pragma omp section        {            test(4);        }    }    /*并行内容*/    printf("运行时间为:%dms\n", clock() - beginClock);//输出图像处理花费时间信息      system("pause");}
    运行时间是211ms,也比单线程运行快了不少实现了并行加速。 
    上面所说到的是OpenMP两个最为基础的使用,当然其功能远远不止这些,如如何避免内存操作冲突之类的,后面如果有用到再放上来。




0 0
原创粉丝点击