/*
Code based on: https://bitbucket.org/icl/papi/wiki/PAPI-Parallel-Programs
*/
#include <papi.h>
#include "mpi.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
void handle_error (int retval);
int main(int argc, char *argv[] )
{
{
int done = 0, n, myid, numprocs, i, rc, retval, EventSet = PAPI_NULL;
double PI25DT = 3.141592653589793238462643;
double mypi, pi, h, sum, x, a;
long_long values[1] = {(long_long) 0};
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
/* Initialize the PAPI library */
retval = PAPI_library_init(PAPI_VER_CURRENT);
if (retval != PAPI_VER_CURRENT) {handle_error(retval);
}
/* Create an EventSet */
retval = PAPI_create_eventset(&EventSet);
if (retval != PAPI_OK){ handle_error(retval);}
/* Add Total Instructions Executed to our EventSet */
retval = PAPI_add_event(EventSet, PAPI_TOT_INS);
if (retval != PAPI_OK){ handle_error(retval);}
/* Start counting */
retval = PAPI_start(EventSet);
if (retval != PAPI_OK){ handle_error(retval);}
n = 50;
for(int n = 50; n <= 150; n += 50)
{
if (myid == 0) {
printf("n = %i\n",n);
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
h = 1.0 / (double) n;
sum = 0.0;
for (i = myid + 1; i <= n; i += numprocs) {
x = h * ((double)i - 0.5);
sum += 4.0 / (1.0 + x*x);
}
mypi = h * sum;
MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0,MPI_COMM_WORLD);
if (myid == 0){
printf("pi is approximately %.16f, Error is %.16f\n", pi, fabs(pi - PI25DT));
}
}
/* Read the counters */
retval = PAPI_read(EventSet, values);
if (retval != PAPI_OK) handle_error(retval);
// printf("After reading counters: %lld\n",values[0]);
/* Start the counters */
retval = PAPI_stop(EventSet, values);
if (retval != PAPI_OK){ handle_error(retval);}
//printf("After stopping counters: %lld\n",values[0]);
}
MPI_Finalize();
exit(0);
}
void handle_error (int retval)
{
printf("PAPI error %d: %s\n", retval, PAPI_strerror(retval));
exit(1);
} |