openMP程序

openMP程序,第1张

openMP 可以拆分循环

比如2个线程,第一个线程负责array 1~5000,第二个线程负责 5001~10000,各循环5000次。这样两个线程可以同时遍历数组的两部分进行搜索计数。4个线程也类似,拆分成4部分同时进行。

#include<stdio.h>

#include<stdlib.h>

#include<omp.h>

#define N 10000

int main(int argc, char *argv[])

{

int i

int array[N]

int count, nthreads, tid, chunk

unsigned num

chunk = 100

count = 0

double start, end

printf("please choose number of threads: 1, 2 or 4.\n")

scanf("%d", &num) //提示输入计算线程数

omp_set_num_threads(num)

#pragma omp parallel shared(nthreads)

{

tid=omp_get_thread_num()

if(tid==0)

{

nthreads=omp_get_num_threads()

printf("\nStarting count with %d threads\n",nthreads)

}

}

start = omp_get_wtime()

#pragma omp parallel for reduction(+:count) schedule(static,chunk)

for( i=0i<Ni++)

{

array[i] = rand() % 10

if(array[i]==3) count++

}

end =omp_get_wtime()

printf("The count cost %f sec. time.\n", end-start )

printf("The number of 3 appeared in the array are %d", count)

}

你说的不能并行,是因为你原来的程序里面没有指定并行进程数目。

你的问题主要在于没有正确的使用reduction(归约)语句

#pragma omp parallel for reduction(+:count) schedule(static,chunk)

for( i=0i<Ni++)

{

array[i] = rand() % 10

if(array[i]==3) count++

}

这里的reduction(+:count)要求每个进程hold一个私有的临时count,并行结束的时候再依次累加到真正的count上面,这样才不会互相干扰各自的计数过程。当然你也可以手工用private参数命令parallel for语句分配私有的临时计数变量,并行结束的时候再用critical语句命令各线程依次把临时计数变量累加到count上。

你用的schedule语句我几乎不用——schedule主要用于自动拆分任务的功能,只有当“每一块任务”执行的时间可能相差很大的时候,才需要采取这种方式。

好比你这里的10000个数,假设拆成4份2500,某组2500花了10ms比完,另一组却要花100ms,那么直接分配四等份就会导致所有进程被100ms的那份任务拖慢。但如果均分的任务本来就可以同时完成(如你要处理的这个问题中一样),那么像这样细分100份100个数,再一次次的喂给四个线程,由于分配任务的耽搁,速度反而变慢……

#include <omp.h>

struct MyData

{

unsigned int value

unsigned int index

}

static struct MyData   Test( unsigned int *p, unsigned int length)

{

#pragma omp parallel for

unsigned int i = 0, res = 0, j = 0

bool  flag = false

struct MyData  d = {0}

for( i = 0 i < length-1 i++ )

{

flag = false

if( p[i] < p[i+1] )

{

res = p[i+1]

flag = true

}

if(flag)

{

j = i+1

}

}

d.value = res

d.index = j

return d

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/11712023.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存