source: CIVL/examples/omp/simple/pi.c.s

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.1 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// // permission obtained
7#include <omp.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <math.h>
11
12void print_usage(char *s) {
13 printf("Usage: %s -i <nr of intervals>\n", s);
14 exit(0);
15}
16
17/* This is the function to integrate */
18double f(double x) {
19 return (4.0 / (1.0 + x*x));
20}
21
22int main (int argc, char *argv[]) {
23
24 const double PI24 = 3.141592653589793238462643;
25 int nthreads, tid;
26 double d, x, sum=0.0, pi;
27 double starttime, stoptime;
28 int n=1000, i;
29 char c;
30
31 /* Check if we have at least one argument */
32// if (argc <=1 ) {
33// print_usage(argv[0]);
34// }
35// else {
36// /* Parse the arguments for a -h or -i flag */
37// while ((c=getopt(argc, argv, "hi:")) != EOF) {
38// switch (c) {
39// case 'h':
40// print_usage(argv[0]);
41// case 'i':
42// n = atoi(optarg); /* Get number of intervals */
43// break;
44 // default:
45// print_usage(argv[0]);
46// }
47// }
48// }
49
50
51 /* Compute the size of intervals */
52 d = 1.0/(double) n;
53
54 /* Start the threads */
55#pragma omp parallel default(shared) private(nthreads, tid, x)
56 {
57 /* Get the thread number */
58 tid = omp_get_thread_num();
59
60 /* The master thread checks how many there are */
61#pragma omp master
62 {
63 nthreads = omp_get_num_threads();
64 printf("Number of threads = %d\n", nthreads);
65 starttime = omp_get_wtime(); /* Measure the execution time */
66 }
67
68 /* This loop is executed in parallel by the threads */
69#pragma omp for reduction(+:sum)
70 for (i=0; i<n; i++) {
71 x = d*(double)i;
72 sum += f(x) + f(x+d);
73 }
74 } /* The parallel section ends here */
75
76 /* The multiplication by d and division by 2 is moved out of the loop */
77 pi = d*sum*0.5;
78
79 stoptime = omp_get_wtime();
80 printf("The computed value of Pi is %2.24f\n", pi);
81 printf("The \"exact\" value of Pi is %2.24f\n", PI24);
82 printf("The difference is %e\n", fabs(PI24-pi));
83 printf("Time: %2.4f seconds \n", stoptime-starttime);
84
85 exit(0);
86}
Note: See TracBrowser for help on using the repository browser.