我正在研究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的
感谢您的任何答复