OpenMp 并行加速

11 篇文章 0 订阅

OpenMp是由OpenMP Architecture Review Board牵头提出的,并已被广泛接受的,用于共享内存并行系统的多线程程序设计的一套指导性注释(Compiler Directive)。OpenMP支持的编程语言包括C语言、C++和Fortran;而支持OpenMp的编译器包括Sun Compiler,GNU Compiler和Intel Compiler等。OpenMp提供了对并行算法的高层的抽象描述,程序员通过在源代码中加入专用的pragma来指明自己的意图,由此编译器可以自动将程序进行并行化,并在必要之处加入同步互斥以及通信。

 

下面先看一段不使用OpenMP的程序:

  1. #include <stdio.h>  
  2. #include <time.h>  
  3. #include <stdlib.h>  
  4.   
  5. void test(int n)  
  6. {  
  7.     for (int i = 0; i< 10000; i++)  
  8.     {  
  9.     }  
  10. }  
  11.   
  12. int main()  
  13. {  
  14.     double dResult;  
  15.     long lBefore = clock();  
  16.     for (int i = 0; i < 10000; i++)  
  17.         test(i);  
  18.     dResult = (double)(clock() - lBefore);  
  19.     printf("\nTotal Time: %f ms.\n", dResult);  
  20.     system("pause");  
  21.     return 0;  
  22. }  
  23. <span style="font-size:18px;"></span>  

程序运行结果如下所示:


再看相同的程序但使用OpenMP的例子:

  1. #include <stdio.h>  
  2. #include <time.h>  
  3. #include <stdlib.h>  
  4. #include <omp.h>  
  5.   
  6. void test(int n)  
  7. {  
  8.     for (int i = 0; i< 10000; i++)  
  9.     {  
  10.   
  11.     }  
  12. }  
  13.   
  14. int main()  
  15. {  
  16.     double dResult;  
  17.     long lBefore = clock();  
  18. #pragma omp parallel for  
  19.     for (int i = 0; i < 10000; i++)  
  20.         test(i);  
  21.     dResult = (double)(clock() - lBefore);  
  22.     printf("\nTotal Time: %f ms.\n", dResult);  
  23.     system("pause");  
  24.     return 0;  
  25. }  

程序运行结果如下所示:


对比使用OpenMP前后运行结果,同样的一段程序,运行时间几乎减少了一半(接近40%)。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值