1. 程式人生 > >OpenMP VS2010配置使用OpenMP

OpenMP VS2010配置使用OpenMP

        一個簡單的OpenMP例子

 

       首先啟動VisualStudio 2010,新建一個C++的控制檯應用程式,如下圖所示:

       然後在專案解決方案資源管理器上選擇專案名稱,點選右鍵,選擇“屬性”,如下圖所示:

 

 

       然後在屬性頁上左側選擇“配置屬性”——“C/C++”——“語言”,然後在右側“OpenMP支援”後選擇“是(/openmp)”,如下圖所示:

 

 

       在cpp檔案中新增如下程式碼:

#include "stdafx.h"

#include<omp.h>

#include<iostream>

usingnamespace std;


//迴圈測試函式
void test()
{
for(int i=0;i<10000;i++)
{

}
}


int _tmain(int argc,_TCHAR* argv[])
{
cout<<"這是一個序列測試程式!\n"
; double start = omp_get_wtime( );//獲取起始時間 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( );//獲取起始時間


#pragma ompparallel for
for(inti = 0; i < 10000; i++) 
{
test();
}


doubleend = omp_get_wtime( );

cout<<"計算耗時為:"<<end -start<<"\n";

cin>>end;

return0;
}

       同樣,也經過10次隨機的執行,其平均耗時約為0.06358044s,兩種不同執行方式的比較結果如下表所示:

 

次數

序列

並行

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

平均值

0.283273

0.06358044

 

       兩種執行方式的結果如下圖所示:

 

       從上面的分析結果可見,採用OpenMP並行所耗時間僅為序列的22.44%,節約近4.5倍的時間。

相關程式原始碼下載地址:
http://download.csdn.net/detail/xwebsite/3843187

再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!https://www.cnblogs.com/captainbed