VS OpenMP基础使用

来源:互联网 发布:宏观经济数据分析 编辑:程序博客网 时间:2024/06/05 05:57

      openMP支持的编程语言包括C语言、C++和Fortran,支持OpenMP的编译器包括Sun Studio,Intel Compiler,Microsoft Visual Studio,GCC。

      OpenMP是CPU并行加速相关的编译处理方案,VS很早的版本就对其提供了支持,不过默认是关闭的。要开启这一支持,只需要在项目的属性中设置就可以,具体选项为:配置属性->C/C++->语言 在右侧列表中有一项“OpenMP 支持”,下拉选择“是(/openmp)”就可以了。 


    

      其实本人是在前几天才知道有这个东西存在的,朋友跟我说这个东西用起来相比正常的开启多线程要方便很多,经过研究发现其确有方便之处。好吧,下面还是写一下它该怎么用吧,这里只是写最基本的,当然后面用到相关的也会加上去。 

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

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

[cpp] view plaincopy
  1. #include <stdio.h>   
  2. #include <time.h>  
  3. #include <stdlib.h>     
  4.   
  5. void test(int time)//纯粹浪费时间  
  6. {  
  7.     int add = 0;  
  8.     for (int runtime = 0; runtime < 100000000; runtime++)  
  9.         add++;  
  10.     printf("%d\n", time);  
  11. }  
  12.   
  13. void main()  
  14. {  
  15.     int beginClock = clock();//记录开始时间  
  16.   
  17.     /*并行内容*/  
  18. #pragma omp parallel sections  
  19.     {  
  20.         #pragma omp section  
  21.         {  
  22.             test(1);  
  23.         }  
  24.         #pragma omp section  
  25.         {  
  26.             test(2);  
  27.         }  
  28.         #pragma omp section  
  29.         {  
  30.             test(3);  
  31.         }  
  32.         #pragma omp section  
  33.         {  
  34.             test(4);  
  35.         }  
  36.     }  
  37.     /*并行内容*/  
  38.   
  39.     printf("运行时间为:%dms\n", clock() - beginClock);//输出图像处理花费时间信息    
  40.     system("pause");  
  41. }  
    运行时间是211ms,也比单线程运行快了不少实现了并行加速。 
    上面所说到的是OpenMP两个最为基础的使用,当然其功能远远不止这些,如如何避免内存操作冲突之类的,后面如果有用到再放上来。


0 1