#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
 
// This can not be larger because of the resolution of the float data type
#define NUMLOOPS 67108860
 
static double deltime(struct timeval *end, struct timeval *begin)
{
  double rv = (end->tv_usec - begin->tv_usec) * 1e-6;
  rv       += (end->tv_sec - begin->tv_sec);
  return rv;
}
 
// pi = 4 * (1/1 - 1/3 + 1/5 - 1.7 ...)
static float pi_float()
{
  float rv = 0;
 
  for (float i=1; i<NUMLOOPS; i += 4.0f) {
    rv += (1.0f / i) - (1.0f / (i+2.0f));
  }
 
  return 4.0f * rv;
}
 
static double pi_double()
{
  double rv = 0;
 
  for (double i=1; i<NUMLOOPS; i += 4.0) {
    rv += (1.0 / i) - (1.0 / (i+2.0));
  }
 
  return 4.0 * rv;
}
 
int main() {
  struct timeval startTime, endTime;
 
  gettimeofday(&startTime, NULL);
  float fpi = pi_float();
  gettimeofday(&endTime, NULL);
  printf("Float Pi generation took %0.3f s and yields %.9f\n",
  deltime(&endTime, &startTime), fpi);
 
  gettimeofday(&startTime, NULL);
  double dpi = pi_double();
  gettimeofday(&endTime, NULL);
  printf("Double Pi generation took %0.3f s and yields %.9f\n",
  deltime(&endTime, &startTime), dpi);
}
