#include "pch.h"
#include "CTic.h"

// 高精度定时器的频率，单位Hz，调用Init()确定
// 目前测到频率在2.5M - 10M
int64_t CTic::Freq = 0;
// 高精度定时器的频率，单位kHz，调用Init()确定
int64_t CTic::Freq_1k = 0;
int64_t CTic::Freq_10k = 0;
int64_t CTic::Freq_100k = 0;
int64_t CTic::Freq_M10 =0;	//0.1Hz
int64_t CTic::Freq_M100 =0;	//0.01Hz
// 记录启动软件时的时间戳
int64_t CTic::AppStartTick = 0;


bool CTic::Init()
{
	if (Freq == 0) { // 确保只调用一次，避免多次调用后AppStartTick发生变化
		QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER*>(&Freq));
		QueryCnt(AppStartTick);
	}
	Freq_1k   = Freq / 1000;
	Freq_10k  = Freq / 10000;
	Freq_100k = Freq / 100000;
	
	Freq_M10 = Freq * 10;
	Freq_M100 = Freq * 100;

	bool ok = (Freq_100k * 100000 == Freq);
	_ASSERT_EXPR(ok, "Freq_100k * 100000 == Freq"); // 必须满足频率是100k的倍数
	return ok; 
}

int64_t CAvgDiffTick::add(int64_t newvalue)
{
	if (!Buf) return 0;
	if (Cnt == 0) {
		index = 0;
		_Avg = 0;
	}
	else if (Cnt < N) {
		_Avg = int((newvalue - Buf[0]) / Cnt);
	}
	else {
		if (index >= N) index = 0;
		_Avg = int(((newvalue - Buf[index]) + N / 2) / N);
	}
	Buf[index] = newvalue;
	index++;
	Cnt++;
	return _Avg;
}

// 测试代码
void CAvgDiffTick::Test1(int avgnum)
{
	CAvgDiffTick Avg(avgnum);
	int64_t x = 0;
	for (int i = 0; i < 100; i++)
	{
		x += 1000 + rand() % 10 - 5;
		std::cout << Avg.add(x) << std::endl;
	}
}

void CAvgDiffTick::Test2(int avgnum)
{
	CAvgDiffTick Avg(avgnum);
	int64_t x = 0;
	for (int i = 0; i < 100; i++)
	{
		std::cout << Avg.add(Avg.appRun_100us()) << std::endl;
		Sleep(100);
	}
}