1: //
2: // reduction --pi
3: //
4: #include <omp.h>
5: #include <stdio.h>
6: #include <math.h>
7:
8: const int n=100000000;
9:
10: inline double f(double x)
11: {
12: return 4/(x*x+1);
13: }
14:
15: int main()
16: {
17: int i, j, nthreads, tid, m = n/2, max_num = 100;
18: int N[] = {1,2,4,8};
19: double T[4], T0, T1;
20: double a = 0.0, b = 1.0, mypi = 0.0;
21: double h = (b-a)/n;
22:
23: for(i=0; i<4; i++)
24: {
25: nthreads = N[i];
26: T0 = omp_get_wtime();
27: mypi = 0.0;
28: for(j = 0;j<max_num;j++)
29: {
30: #pragma omp parallel num_threads(nthreads) reduction(+:mypi) private(i,
tid)
31: {
32:
33: tid = omp_get_thread_num();
34: for (i=tid+1; i<=m; i=i+nthreads)
35: {
36: mypi = mypi + 4*f(a+(2*i-1)*h);
37: if(i<m)
38: mypi = mypi+2*f(a+2*i*h);
39: }
40: }
41: mypi = mypi+f(a);
42: mypi = mypi*(h/3);
43: if(j == max_num-1)
44: printf("mypi = %.10f, ",mypi);
45: }
46:
47: T1 = omp_get_wtime();
48: T[i] = T1 - T0;
49: // if(i>0)
50: printf("nthreads=%d, time=%.2f, speedup=%.2f", nthreads, T[i], T[0]/T[i]);
51: }
52:
53: return 0;
54: }
评论12