我正在研究openMP中的代碼。代碼必須在文件中打印2到1000000之間的所有素數。串行算法需要150秒來完成所有計算,其中兩個線程export OMP_NUM_THREADS=2
代碼在81秒內運行(意味着加速等於1.85)。但多達2 export OMP_THREADS=3,4
線程,加速不會改變。它仍然等於〜1.8。如何在我的代碼中使線程加速超過3個線程?
我也改變了調度沒有任何改變。
我的代碼在哪裏primes.cpp。你可以過去,在你的編輯器複製並與以下行編譯命令:
~$ g++ primes.cpp -o primes -fopenmp
變化過程中,以2(不管你喜歡或)數量
~$ export OMP_NUM_THREADS=2
變化任務調度(靜態,動態,制導)
~$ export OMP_SCHEDULE=dynamic,100000
與
~$ ./primes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <algorithm>
#include <time.h>
#include <omp.h>
#define SIZE 1000000
using namespace std;
int main(){
// code permettant derecuperer dans un fichier la liste des
// nombres premiers entre O et SIZE
// variables
int cprime;
int chunk;
int lap, loop, i;
int isprime;
int count;
FILE * file;
char * filename;
time_t t1;
vector<int>primelist;
int thread_num;
//omp_sched_t schedule;
// initialisation
t1 = time(NULL);
chunk = 100000;
count = 0;
filename = (char *) malloc(sizeof(char)*100);
strcpy(filename, "primes.txt");
file = fopen(filename, "w");
// ------------- ALGORITHME ---------------
#pragma omp parallel private(thread_num)
{
thread_num = omp_get_thread_num();
if(thread_num == 0)
printf("%d processor are available for work\n", omp_get_num_threads());
#pragma omp barrier
#pragma omp critical
{
printf("I'm processor %d ready for work\n", thread_num);
}
}
#pragma omp parallel for private(cprime, loop, isprime) schedule(runtime) shared(primelist) reduction(+:count)
for(cprime = 2; cprime < SIZE; cprime++){
loop = 1;
isprime = 1;
// looking if it's a prime number
while((++loop<cprime) && isprime){
if(cprime % loop == 0) isprime = 0;
}
if(isprime) {
#pragma omp critical
{
primelist.push_back(loop);
}
count++;
}
#pragma omp critical
{
if(cprime % chunk == 0)
printf("Indicator from thread %d current(size N) : %d\n",omp_get_thread_num(), cprime);
}
}
sort(primelist.begin(), primelist.end());
lap = primelist.size();
for(i = 0; i < lap; i++)
fprintf(file, "%d\n", primelist[i]);
fclose(file);
printf("%d primes where discover between 0 and %d, duration of the operation %d\n", count, SIZE, (int) difftime(time(NULL), t1));
return 0;
}
運行環境信息運行
我的電腦有4個處理器
我已經驗證它在那裏說明從processor : 0
轉到文件/proc/cpuinfo
在processor 3
。都是英特爾(R)酷睿(TM)i5的CPU中號600 @ 2.53GHz的
感謝您的任何答覆