#include "lp_profiler.h"

#include <time.h>
#include <stdio.h>

LP_ProfilePoint::LP_ProfilePoint(char *aName, char* aFile, int aLine)
{
  startTime = clock();
  name = aName;
  file = aFile;
  line = aLine;
}

LP_ProfilePoint::~LP_ProfilePoint()
{
  clock_t stopTime = clock();
  LP_Profiler* profiler = LP_Profiler::GetInstance();
  profiler->Add(name, file, line, stopTime - startTime);
}

////////////////////////////////////////////////////////////////////////////

LP_Profiler* ourInstance = NULL;

LP_Profiler::LP_Profiler()
{
}

LP_Profiler::~LP_Profiler()
{
}

LP_Profiler*
LP_Profiler::GetInstance()
{
  if(!ourInstance)
    ourInstance = new LP_Profiler();
  return ourInstance;
}

void
LP_Profiler::Destroy()
{
  if(ourInstance)
    delete ourInstance;
  ourInstance = NULL;
}

void
LP_Profiler::Add(char *aName, char *aFile, int aLine, int accTime)
{
  bool found = false;

  for(int i = 0; i < tasks.Count(); i++)
  {
    Task& t = tasks[i];
    if(t.line == aLine && strcmp(t.file, aFile) == 0)
    {
      t.accTime += accTime;
      t.numExecs++;
      found = true;
      break;
    }
  }

  if(!found)
    tasks.Add(Task(aName, aFile, aLine, accTime));
}

void
LP_Profiler::Print()
{
  for(int i = 0; i < tasks.Count(); i++)
  {
    Task& t = tasks[i];
    if(t.numExecs > 0)
    {
      float totalTime = (float) t.accTime / (float) CLOCKS_PER_SEC;
      float avgTime = totalTime / (float) t.numExecs;
      printf("%s, avg: %.8fs, tot: %.8fs, num: %d\n", t.name, avgTime, totalTime, t.numExecs);
    }
  }
}
