也許有人會不相信第一個OpenMP程式是用4核心(我的電腦是4核心)來跑,那麼我來做以下的實驗。
程式碼跟上一篇一樣,只是加了計算時間的程式碼和增加for迴圈空轉次數1000000000(10億)。
/**
Theme: My Second OpenMP Program
Compiler: Visual Studio 2010 Professional
Date: 100/10/20
Author: HappyMan
Blog: https://cg2010studio.wordpress.com/
*/
#include <omp.h>
#include <iostream>
#include <iomanip>
#include <windows.h>
void test( int n )
{
for( int i = 0; i < 1000000000; ++ i )
{
//do nothing, just waste time
}
printf( "%d, ", n );
//std::cout<< n << ", ";
}
int main(int argc, char* argv[])
{
LARGE_INTEGER startTime,endTime,fre;
double times;
QueryPerformanceFrequency(&fre); //取得CPU頻率
QueryPerformanceCounter(&startTime); //取得開機到現在經過幾個CPU Cycle
#pragma omp parallel for
for( int i = 0; i < 10; ++ i )
test( i );
QueryPerformanceCounter(&endTime); //取得開機到程式執行完成經過幾個CPU Cycle
times=((double)endTime.QuadPart-(double)startTime.QuadPart)/fre.QuadPart;
std::cout << std::endl << std::fixed << std::setprecision(20) << times << std::endl;
system( "pause" );
}
執行的結果:
6, 8, 3, 0, 7, 9, 4, 1, 5, 2,
9.02410130783111340000
請按任意鍵繼續 . . .
看一下各CPU的狀況:
接著註解掉#include <omp.h>和#pragma omp parallel for這兩行後的執行結果:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
29.38177881697883000000
請按任意鍵繼續 . . .
這是1顆核心跑出來的結果,跟4顆核心的時間相比,大概是3.2倍。接下來看各個CPU的狀況:


隨意留個言吧:)~