(原創) 如何在VC8使用OpenMP? (C/C++) (VC++) (OpenMP)

來源:互聯網
上載者:User

Abstract
隨著多核心CPU普及,但時脈卻越來越低,若程式還是用單核心的方式去寫,不僅壓榨不出多核心的效能,執行速度還可能越來越低,所以使用平行處理(Parallel Programming)也就越來越重要了。

Introduction
相信很多人都有感覺,換了Core 2 Duo後,發現執行速度並沒有Pentium IV來的快,主要是因為Core 2 Duo的時脈都沒Pentium IV高,若程式還是用單核心的寫法,並無法發揮出多核心的效能。OpenMP可以讓你簡單的撰寫平行化的程式,盡量榨乾多核心CPU,讓你的程式跑得更快,如7Zip就是一個很好的例子,在多核心下壓縮速度驚人,遠遠超越WinRAR。

OpenMP on VC8
OpenMP是Intel提出的標準,目前已經被Visual C++和gcc所支援,所以可以利用OpenMP撰寫出跨平台的平行化程式。

Step 1:
設定支援OpenMP

選擇專案名稱,右鍵Properties,左側Configuration Properties -> C/C++ -> Language,右側將OpenMP Support選Yes(/openmp)

Step 2:
測試Hello World平行處理版

C語言

1 /* 
2 (C) OOMusou 2008 http://oomusou.cnblogs.com

4 Filename    : parallel_helloworld.cpp
5 Compiler    : Visual C++ 8.0
6 Description : Demo how to use hello world in parallel programming
7 Release     : 03/05/2008 1.0
8 */
9 #include <stdio.h>
10 #include "omp.h"
11 
12 int main() {
13   printf("Number of core : %d\n", omp_get_num_procs());
14   printf("Number of threads : %d\n", omp_get_num_threads());
15    
16   #pragma omp parallel for
17   for(int i = 0; i < 16; ++i) {
18     printf("thread %d print Hello World!!\n", omp_get_thread_num());
19   } 
20 }

執行結果

Number of core : 2
Number of threads : 1
thread 0 print Hello World!!
thread 1 print Hello World!!
thread 0 print Hello World!!
thread 0 print Hello World!!
thread 1 print Hello World!!
thread 0 print Hello World!!
thread 0 print Hello World!!
thread 1 print Hello World!!
thread 0 print Hello World!!
thread 1 print Hello World!!
thread 0 print Hello World!!
thread 1 print Hello World!!
thread 0 print Hello World!!
thread 1 print Hello World!!
thread 1 print Hello World!!
thread 1 print Hello World!!

若能執行成功,表示已經在VC8設定出OpenMP的執行環境。

和ANSI C不同的是,第10行多了#include "omp.h",這是OpenMP的header file,在16行多了#pragma directive,表示以下的for loop需要平行化,如此一來我們可以發現Hello World分別以兩個thread進行列印,充分利用了兩個核心。

Conclusion
我覺得OpenMP最大的貢獻在於,只需對原本單核心的程式做小幅度的修改,就變成可以支援多核心的程式,而且又是個開放的標準,所以可移植性沒問題。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.