#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <chrono>

#define MAX_TIME 1000
#define ABNORMAL_THRESHOLD 0.1

int main() {
	while(1) {
		double maxTime = 0;
		double minTime = 1000;
		double averageTime = 0;
		// double startTime = clock() / (double)CLOCKS_PER_SEC * 1000;
		auto startTime = std::chrono::high_resolution_clock::now();
		int count = 0;
		int countAbnormal = 0;
		float abnormalTotal = 0;
		// double lastNow = 0;
		auto lastNow = startTime;
		while(1) {
			// double now = clock() / (double)CLOCKS_PER_SEC * 1000;
			auto now = std::chrono::high_resolution_clock::now();
			// double delta = now - lastNow;
			double delta = std::chrono::duration_cast<std::chrono::nanoseconds>(now - lastNow).count() / 1000000.0;
			double startDelta = std::chrono::duration_cast<std::chrono::nanoseconds>(now - startTime).count() / 1000000.0;
			lastNow = now;
			// wait for 20ms to start measurement
			if(startDelta > 20) {
				maxTime = fmax(maxTime, delta);
				minTime = fmin(minTime, delta);
				averageTime += delta;
				count++;
				if(delta > ABNORMAL_THRESHOLD){
					countAbnormal++;
					abnormalTotal += delta;
				}
			}
			if(startDelta > MAX_TIME) {
				break;
			}
		}
		averageTime /= count;
		//printf("max: %f min: %f ave: %f count:%i\n", maxTime, minTime, averageTime, count);
		printf("max: %f min: %f ave: %f count:%i abnormal:%i abnormalTotal:%f\n", maxTime, minTime, averageTime, count, countAbnormal, abnormalTotal);
	}
}

// g++ -O3 -o latency.exe latency.cpp & latency.exe