Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Program to compute Pi using Monte Carlo methods */
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <math.h>
- #include <string.h>
- #include <time.h>
- #include <sys/sysinfo.h>
- #define SEED 35791246
- #define uint unsigned long
- #define c_unit const unsigned long
- #define THREADS omp_get_max_threads()
- void init_arr(uint* const arr )
- {
- for (uint i=0; i<THREADS; ++i) arr[i] = 0;
- }
- void main(const int argc, char** const argv)
- {
- uint count = 0;
- c_unit iters = strtol(argv[1],argv+2,10);
- uint results[THREADS];
- init_arr(results);
- clock_t begin = clock();
- int randomData = open("/dev/urandom", O_RDONLY);
- #pragma omp parallel for
- for (uint i = 0; i<iters; ++i)
- {
- double x,y ;
- unsigned int buff;
- pread(randomData,&buff,4,0);
- buff %= RAND_MAX;
- x = (double) buff / RAND_MAX;
- pread(randomData,&buff,4,0);
- buff %= RAND_MAX;
- y = (double) buff / RAND_MAX;
- if ((x*x+y*y)<=1) results[omp_get_thread_num()]++;
- }
- for (uint i=0; i<THREADS; ++i) count += results[i];
- double pi=(double)count/iters*4;
- printf("# of trials= %li , estimate of pi is %g \n",iters,pi);
- clock_t end = clock();
- double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
- printf("\n time spent is: %f ms\n",time_spent);
- close(randomData);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement