/*
    PIP - Platform Independent Primitives
    System tests program
    Copyright (C) 2014  Ivan Pelipenko peri4ko@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "pip.h"
#include "pisystemtests.h"


int main(int argc, char * argv[]) {
#ifdef WINDOWS
	cout << "This program is useless for Windows" << endl;
	return 0;
#else
	if (getuid() != 0) {
		cout << "You should run this program as root!" << endl;
		return 0;
	}
	PIConfig conf(
#ifndef WINDOWS
		"/etc/pip.conf"
#else
		"pip.conf"
#endif
	);
	PITimeMeasurer timer, tm;
	timespec ts;
	long stc = 0;
	double st;
	llong sts = 0;
	clock_getres(CLOCK_REALTIME, &ts);
	stc = long(ts.tv_sec) * 1000000000l + long(ts.tv_nsec);
	conf.setValue("time_resolution_ns", stc);
	cout << "Timer resolution is " << stc << " ns" << endl;
	
	cout << "\"PITimer.elapsed_*\" test ... " << flush;
	stc = 0;
	ts.tv_sec = 0;
	ts.tv_nsec = 1000;
	PIVector<double> times;
	times.resize(8192);
	tm.reset();
	PISystemTests::time_elapsed_ns = 0;
	while (tm.elapsed_s() < 3.) {
		for (int i = 0; i < times.size_s(); ++i) {
			timer.reset();
			times[i] = timer.elapsed_m();
			times[i] = timer.elapsed_s();
			times[i] = timer.elapsed_u();
		}
		st = 0;
		for (int i = 0; i < times.size_s(); ++i)
			st += times[i];
		//cout << times[0] << endl;
		//cout << st / times.size_s() / 3. * 1000. << endl;
		sts += piRoundd(st / times.size_s() / 3. * 1000.);
		//cout << sts << endl;
		stc++;
	}
	sts /= stc;
	conf.setValue("time_elapsed_ns", long(sts));
	cout << "ok, cost " << sts << " ns, average in " << stc << " series (" << (stc * 3 * times.size_s()) << " executes)" << endl;
	
	cout << "\"usleep\" offset test ... " << flush;
	PISystemTests::time_elapsed_ns = sts;
	tm.reset();
	stc = 0;
	sts = 0;
	times.resize(128);
	while (tm.elapsed_s() < 3.) {
		for (int i = 0; i < times.size_s(); ++i) {
			timer.reset();
			usleep(1000);
			times[i] = timer.elapsed_u();
		}
		st = 0;
		for (int i = 0; i < times.size_s(); ++i)
			st += times[i] - 1000;
		//cout << times[0] << endl;
		//cout << st / times.size_s() / 3. * 1000. << endl;
		sts += piRoundd(st / times.size_s());
		//cout << sts << endl;
		stc++;
	}
	sts /= stc;
	conf.setValue("usleep_offset_us", long(sts));
	cout << "ok, " << sts << " us, average in " << stc << " series (" << (stc * times.size_s()) << " executes)" << endl;
	
	//WAIT_FOR_EXIT
	return 0;
#endif
};
