module cache_bench;

import std.stdio;
import std.algorithm;
import std.range;
import core.sys.posix.fcntl;
import core.sys.posix.unistd;
import core.time;

enum fileName = "test.file";

void recreateFile() {
	// (re)create an empty file
	remove(fileName);
	auto f = creat(fileName, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
	close(f);
	sync();
	sleep(3);
}

void main()  
{
	byte[] data;
	data.length = 1024 * 1024;
	copy(map!"cast(byte)a"(iota(0, data.length, 1)), data);

	recreateFile();

	auto f = open(fileName, O_WRONLY);
	stdout.write("Testing default behaviour... ");
	stdout.flush;
	auto start = TickDuration.currSystemTick();
	core.sys.posix.unistd.write(f, data.ptr, data.length);
	close(f);
	stdout.writeln((TickDuration.currSystemTick() - start).usecs, " μs");

	recreateFile();
	
	f = open(fileName, O_WRONLY | O_SYNC);
	stdout.write("Testing O_SYNC behaviour... ");
	stdout.flush;
	start = TickDuration.currSystemTick();
	core.sys.posix.unistd.write(f, data.ptr, data.length);
	close(f);
	stdout.writeln((TickDuration.currSystemTick() - start).usecs, " μs");
	
	recreateFile();

	f = open(fileName, O_WRONLY);
	stdout.write("Testing fsync() behaviour... ");
	stdout.flush;
	start = TickDuration.currSystemTick();
	core.sys.posix.unistd.write(f, data.ptr, data.length);
	fsync(f);
	close(f);
	stdout.writeln((TickDuration.currSystemTick() - start).usecs, " μs");
}
