#include "benchmark.h"
#include "system.h"
#include "stdlib.h"
#include "stdio.h"
#include "stdint.h"
#include "../sort/sort.h"
#include "../common/common.h"

static uint32_t sort_lock;

int _benchmark_sort (unsigned int size)
{
  printf("\n");
  printf("================================\n");
  printf("Benchmark Sort\n");
  printf("================================\n");
  printf("\n");

  printf(" * Size : %d\n",size);

  unsigned int* SortArray;
  
  int cycle_begin, result;

  result = 0;
  
  int p=procnum();
  
  sort_t _sort_type;
  const sort_t nb_sort_type = 4;
  
  for (_sort_type=0; _sort_type < nb_sort_type; _sort_type++)
    {
      sort_t sort_type = (_sort_type+p)%nb_sort_type;
      
      printf(" * Algo : %s\n",sort_str(sort_type));
      
      printf("   * Init...\n");
      
      lock_lock(&sort_lock);
      SortArray = (unsigned int*) malloc(size*sizeof(unsigned int));
      lock_unlock(&sort_lock);
      
      unsigned int seed = p;
      int i;
      for (i=0; i<size; ++i)
        {
          seed = seed * 1103515245 + 12345;
          SortArray[i] = seed&0xff;
        }
      printf("   * Sort... \n");
      
      cycle_begin = cpu_cycles();
      sort((unsigned int *) (SortArray), (unsigned int) size, sort_type);
      int cycle_exec = cpu_cycles()-cycle_begin;
      
      printf("   * Executed in %d cycles\n",cycle_exec);
      
      result += cycle_exec;
      
      printf("   * Verification... ");
      
      for (i = 1; i < size; i++)
        {
          /* printf("%d ",SortArray[i-1]); */
          
          if (SortArray[i] < SortArray[i-1])
            {
              printf("KO !!!\n");
              EXIT(1);
            }
        }
      printf("OK\n");

      free (SortArray);

    }
  
  return result;
}

int benchmark_sort (void) { return _benchmark_sort(SORT_SIZE); }

  
