#define MAXVSIZE 1000
#include <stdio.h>
#include <libcpc.h>
#include <errno.h>

void loop(double c[], double a[], double b[], int n) {
   int i;

   for (i=0;i<n;i++)
     c[i] = a[i] + b[i];
}


int main() {

     double a[MAXVSIZE], b[MAXVSIZE], c[MAXVSIZE];
     int i,n;

     int cpuver, iter;
     char *setting = NULL;
     cpc_event_t event;
     cpc_event_t before, after;
     long long pic0 = 0, pic1 = 0;
     long long cycles = 0;
     long long instrs = 0;


     printf("Enter vector size:  ");
     scanf("%d",&n);

     for (i=0;i<n;i++) {
       a[i] = i;
       b[i] = n-i;
     }

/* Count instructions and cycles with cpc */

     if ((cpuver = cpc_getcpuver()) == -1) 
     { 
	printf("No performance counters available!\n"); 
	exit(-1); 
     }

/* start counting */

     if (cpc_strtoevent(cpuver, "pic0=Cycle_cnt,pic1=Instr_cnt", &event) != 0)
	printf("ev : cannot measure %s\n", setting);
       
     setting = cpc_eventtostr(&event);

     if (cpc_bind_event(&event,0) == -1)
	printf("cannot bind lwp %d %s\n", _lwp_self(), strerror(errno));

     cpc_take_sample(&before);
     loop(c,a,b,n);
     cpc_take_sample(&after);
     pic0 =  ( after.ce_pic[0] - before.ce_pic[0]) ;
     pic1 =  ( after.ce_pic[1] - before.ce_pic[1]) ;
     cycles = pic0;
     instrs = pic1;

     printf("%15.0f instructions in %15.0f cycles\n",
       (double) instrs, (double) cycles);

    for (i=0;i<n;i++)
      printf("c[%d] = %g\n",i,c[i]);
}
