source: CIVL/examples/omp/pi_orphan.c

main
Last change on this file was ea777aa, checked in by Alex Wilton <awilton@…>, 3 years ago

Moved examples, include, build_default.properties, common.xml, and README out from dev.civl.com into the root of the repo.

git-svn-id: svn://vsl.cis.udel.edu/civl/trunk@5704 fb995dde-84ed-4084-dfe6-e5aef3e2452c

  • Property mode set to 100644
File size: 2.3 KB
Line 
1/*
2 OpenMP example program that computes the value of Pi using the trapeziod rule.
3 Compile with gcc -fopenmp -O3 omp_pi.c -o omp_pi
4*/
5// Online source: http://users.abo.fi/mats/PP2012/examples/OpenMP/omp_pi.c
6// Modified pi.c to add an orphan
7#include <omp.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <math.h>
11#include <assert.h>
12
13#ifdef _CIVL
14$input int N=100;
15#else
16#define N 1000
17#endif
18
19double starttime, d, x, sum = 0.0;
20int nthreads;
21int n=N;
22
23void print_usage(char *s) {
24 printf("Usage: %s -i <nr of intervals>\n", s);
25 exit(0);
26}
27
28/* This is the function to integrate */
29double f(double x) {
30 return (4.0 / (1.0 + x*x));
31}
32
33float piOrphan(){
34 /* The master thread checks how many there are */
35 int i;
36#pragma omp master
37 {
38 nthreads = omp_get_num_threads();
39 printf("Number of threads = %d\n", nthreads);
40 starttime = omp_get_wtime(); /* Measure the execution time */
41 }
42
43 /* This loop is executed in parallel by the threads */
44#pragma omp for reduction(+:sum)
45 for (i=0; i<n; i++) {
46 x = d*(double)i;
47 sum += f(x) + f(x+d);
48 }
49}
50
51int main (int argc, char *argv[]) {
52
53 const double PI24 = 3.141592653589793238462643;
54 int tid;
55 double pi;
56 double stoptime;
57 char c;
58
59#ifndef _CIVL
60 /* Check if we have at least one argument */
61 if (argc <=1 ) {
62 print_usage(argv[0]);
63 }
64 else {
65 /* Parse the arguments for a -h or -i flag */
66 while ((c=getopt(argc, argv, "hi:")) != EOF) {
67 switch (c) {
68 case 'h':
69 print_usage(argv[0]);
70 case 'i':
71 n = atoi(optarg); /* Get number of intervals */
72 break;
73 default:
74 print_usage(argv[0]);
75 }
76 }
77 }
78#endif
79
80 /* Compute the size of intervals */
81 d = 1.0/(double) n;
82
83 /* Start the threads */
84#pragma omp parallel default(shared) private(nthreads, tid, x)
85 {
86 /* Get the thread number */
87 tid = omp_get_thread_num();
88
89 piOrphan();
90
91 } /* The parallel section ends here */
92
93 /* The multiplication by d and division by 2 is moved out of the loop */
94 pi = d*sum*0.5;
95
96 stoptime = omp_get_wtime();
97 printf("The computed value of Pi is %2.24f\n", pi);
98 printf("The \"exact\" value of Pi is %2.24f\n", PI24);
99 printf("The difference is %e\n", fabs(PI24-pi));
100#ifdef _CIVL
101 assert(fabs(PI24-pi) < 0.1);
102#endif
103 printf("Time: %2.4f seconds \n", stoptime-starttime);
104
105 exit(0);
106}
Note: See TracBrowser for help on using the repository browser.