#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#include "dist.h"

int main(int argc, char* argv[]){

        int i, dim, n, r;
        double *p1, *p2;
        double d;
        struct timeval tv;
        double time_before, time_after, time_diff;

        // parse command line
        if(argc != 2){
                fprintf(stderr, "[C] Usage: %s <dimensionality>\n", argv[0]);
                exit(-1);
        }
        dim = atoi(argv[1]);
       
        // allocate memory
        p1 = malloc(dim*sizeof(double)); 
        p2 = malloc(dim*sizeof(double));
        if(p1 == NULL || p2 == NULL){
                fprintf(stderr, "ERROR! Could not allocate memory for two vectors of dimension %d!\n", dim);
                exit(-1);
        }

        // generate vectors
        for(i=0; i < dim; i++){
                p1[i] = (double)i+1.0;
                p2[i] = (double)i+2.0;
        }

        // DEBUG: calculate distance once
        d = dist(dim, p1, p2);
        fprintf(stdout, "dist: %lf\n", d);

        // run distance function n times, 
        // until it takes atleast 1s to complete the n runs
        n = 1;
        time_diff = 0.0;
        while(time_diff <= 1.0){
              
                fprintf(stdout, "."); fflush(stdout);
                n *= 2;

                // time before
                r = gettimeofday(&tv, NULL);
                if(r != 0){
                        fprintf(stderr, "ERROR! Problem while using gettimeofday (return value: %d).\n", r);
                        exit(-1);
                }
                time_before = (double)tv.tv_sec + (double)tv.tv_usec/1000000;

                // benchmark
                for(i=0; i < n; i++){
                        d = dist(dim, p1, p2);
                }

                // time after
                r = gettimeofday(&tv, NULL);
                if(r != 0){
                        fprintf(stderr, "ERROR! Problem while using gettimeofday (return value: %d).\n", r);
                        exit(-1);
                }
                time_after = (double)tv.tv_sec + (double)tv.tv_usec/1000000;

                time_diff = time_after - time_before;
                
        }
        fprintf(stdout, "\n Needed %d iterations to achieve 1s of total run time: %lf\n", n, time_diff);

        fprintf(stdout, "Benchmark results: %.3lfns needed per iteration; %.2lf iterations per second\n", time_diff*1e6/n, n/time_diff);

        return 0;
}
