A simple OpenMP example
First start VisualStudio 2010 and create a new C++ console application, as shown below:
Then select the project name on the project solution explorer, right-click, and select "Properties", as shown in the following figure:
Then select "Configuration Properties" - "C/C++" - "Language" on the left side of the property page, and then select "Yes (/openmp)" after "OpenMP Support" on the right side, as shown in the following figure:
Add the following code to the cpp file:
- #include "stdafx.h"
- #include<omp.h>
- #include<iostream>
- usingnamespace std;
- //loop test function
- void test()
- {
- for(int i=0;i<10000;i++)
- {
- }
- }
- int _tmain(int argc,_TCHAR* argv[])
- {
- cout<< "This is a serial test program!\n" ;
- double start = omp_get_wtime( ); //Get the start time
- for(int i = 0; i < 10000; i++)
- {
- test();
- }
- double end = omp_get_wtime( );
- cout<<"计算耗时为:"<<end -start<<"\n";
- cin>>end;
- return 0;
- }
以上代码中红色字体为添加的代码,以上程序是一个典型的串行程序,经过随机运行10次,其平均耗时约0.283273s(具体所耗时间跟测试计算机有密切的关系,测试电脑CPU采用Core I7 2630QM,4核)。
下面将其转换成并行程序,只需要在for循环加上#pragma omp parallel for即可,如下代码(注意红色部分):
- #include "stdafx.h"
- #include<omp.h>
- #include <iostream>
- using namespace std;
- //循环测试函数
- void test()
- {
- for(inti=0;i<10000;i++)
- {
- }
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- cout<<"这是一个并行测试程序!\n";
- doublestart = omp_get_wtime( ); //Get the start time
- #pragma ompparallel for
- for (inti = 0; i <10000; i ++)
- {
- test();
- }
- doubleend = omp_get_wtime( );
- cout<< "Calculation time is:" <<end -start<< "\n" ;
- cin>>end;
- return0;
- }
frequency |
serial |
parallel |
1 |
0.283382 |
0.0746704 |
2 |
0.283654 |
0.0686404 |
3 |
0.283212 |
0.0536631 |
4 |
0.280234 |
0.0517737 |
5 |
0.283041 |
0.0717588 |
6 |
0.283126 |
0.0524264 |
7 |
0.281881 |
0.0580316 |
8 |
0.283301 |
0.0730386 |
9 |
0.284545 |
0.0745088 |
10 |
0.286353 |
0.0572926 |
average value |
0.283273 |
0.06358044 |
The results of the two modes of operation are shown in the following figures:
From the above analysis results, it can be seen that the time consumed by using OpenMP in parallel is only 22.44% of that in serial, which saves nearly 4.5 times the time.