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;
- }
- <span style="font-size:18px;"></span>
程序运行结果如下所示:
再看相同的程序但使用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 for
- for (int i = 0; i < 10000; i++)
- test(i);
- dResult = (double)(clock() - lBefore);
- printf("\nTotal Time: %f ms.\n", dResult);
- system("pause");
- return 0;
- }
程序运行结果如下所示: