#include "PerfChecker.h"
#include <assert.h>
#include <stdio.h>

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif

#ifdef _WIN32
long long Perf_GetTime()
{
	LARGE_INTEGER t;  
	QueryPerformanceCounter(&t);
	return t.QuadPart;
}

double Perf_ConvertTime(long long use_time)
{
	LARGE_INTEGER tc;  
	QueryPerformanceFrequency(&tc);  
	return use_time * 1000.0 / tc.QuadPart;
}

#else
long long Perf_GetTime()
{
	timeval timeVal;
	if(0 == gettimeofday(&timeVal, NULL))
	{
		return (timeVal.tv_sec*1000 * 1000) + (timeVal.tv_usec);
	}

	return 0;
}

double Perf_ConvertTime(long long use_time)
{
	return use_time / 1000.0;
}

#endif

PerfChecker::PerfChecker(const char * pszFunctionName,const char * pszSourceFile,
						 int nLineNum,PERF_CHECK_LEVEL checkLevel)
{
	assert(pszFunctionName && pszFunctionName[0] && pszSourceFile && pszSourceFile[0]);
	m_strFunctionName = pszFunctionName;
	m_strSourceFile = pszSourceFile;
	m_nLineNum = nLineNum;
	m_eCheckLevel = checkLevel;
	m_nStartTime = m_nCheckPointTime = Perf_GetTime();
}

PerfChecker::~PerfChecker(void)
{
//	long long nCurTime = Perf_GetTime();
//	Output(m_strFunctionName.c_str(), m_nStartTime, nCurTime);
}


void PerfChecker::CheckPoint(const char * pszCheckPointName)
{
	long long nCurTime = Perf_GetTime();
	Output(pszCheckPointName, m_nCheckPointTime, nCurTime);

	m_nCheckPointTime = nCurTime;
}

void PerfChecker::Output(const char * pszCheckPointName, long long nStartTime, long long nCurTime)
{
	long long nUseTime = nCurTime - nStartTime;
	double use_time = Perf_ConvertTime(nUseTime);
	printf("<%s> take %.03f ms\n", pszCheckPointName, use_time);
}
