首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

运用OpenMP的一个简单例子

2012-12-26 
使用OpenMP的一个简单例子OpenMp是由OpenMP Architecture Review Board牵头提出的,并已被广泛接受的,用于

使用OpenMP的一个简单例子

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

 

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

#include <stdio.h>#include <time.h>#include <stdlib.h>void test(int n){for (int i = 0; i< 10000; i++){}}int main(){double dResult;long lBefore = clock();for (int i = 0; i < 10000; i++)test(i);dResult = (double)(clock() - lBefore);printf("\nTotal Time: %f ms.\n", dResult);system("pause");return 0;}

程序运行结果如下所示:

运用OpenMP的一个简单例子


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

#include <stdio.h>#include <time.h>#include <stdlib.h>#include <omp.h>void test(int n){for (int i = 0; i< 10000; i++){}}int main(){double dResult;long lBefore = clock();#pragma omp parallel forfor (int i = 0; i < 10000; i++)test(i);dResult = (double)(clock() - lBefore);printf("\nTotal Time: %f ms.\n", dResult);system("pause");return 0;}

程序运行结果如下所示:

运用OpenMP的一个简单例子


对比使用OpenMP前后运行结果,同样的一段程序,运行时间几乎减少了一半(接近40%)。

热点排行