Page MenuHomec4science

pi.c
No OneTemporary

File Metadata

Created
Thu, Aug 29, 17:11
/*
============================================================================
Filename : pi.c
Author : Your names goes here
SCIPER : Your SCIPER numbers
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utility.h"
double calculate_pi (int num_threads, int samples);
int verbose = 0;
int tablemode = 0;
int main (int argc, const char *argv[]) {
int num_threads, num_samples;
double pi;
if (argc < 3) {
printf("Invalid input! Usage: ./pi <num_threads> <num_samples> \n");
return 1;
} else {
num_threads = atoi(argv[1]);
num_samples = atoi(argv[2]);
for (int arg = 3; arg < argc; ++arg) {
if (!strcmp(argv[arg], "-v"))
verbose = 1; // set verbose mode
else if (!strcmp(argv[arg], "-t"))
tablemode = 1; // set table mode
}
}
set_clock();
pi = calculate_pi (num_threads, num_samples);
double ttime = elapsed_time(); // compute it once
if (tablemode)
printf("%d %.15g %.4g\n", num_threads, pi, ttime); // table output mode
else
printf("- Using %d threads: pi = %.15g computed in %.4gs.\n", num_threads, pi, ttime);
return 0;
}
double calculate_pi (int num_threads, int samples) {
double pi;
/* Your code goes here */
omp_set_num_threads(num_threads);
int * sums = malloc(sizeof(int) * num_threads);
int tid;
//int shared_sample = samples / num_threads;
#pragma omp parallel private(tid) shared(num_threads)
{
tid = omp_get_thread_num();
rand_gen gen = init_rand();
sums[tid] = 0;
for(int i = tid; i< samples; i+=num_threads)
{
double x = next_rand(gen);
double y = next_rand(gen);
if (x*x + y*y <= 1)
{
//#pragma omp atomic
//sum++;
++sums[tid];
if (verbose)
printf("Inside: (%f, %f), ID: %d\n", x, y, tid);
}
}
}
int sum = 0;
for (int i = 0; i < num_threads; ++i)
sum += sums[i];
free(sums);
pi = 4.0*(double)sum/(double)samples;
if (verbose)
printf("Total empiric sum: %d", sum);
return pi;
}

Event Timeline