/*
 * DF-2717 microbench -- relative-path open() rate, used to A/B the fix
 * (fd_spin around the nlookup_init cache_copy) for performance impact.
 * 2,000,000 x open("./f") + close on a tmpfs file, best of 3.
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>

static double
now(void)
{
	struct timespec ts;
	clock_gettime(CLOCK_MONOTONIC, &ts);
	return ts.tv_sec + ts.tv_nsec * 1e-9;
}

int main(int argc, char **argv)
{
	const char *path = argc > 1 ? argv[1] : "./f";
	long n = argc > 2 ? atol(argv[2]) : 2000000;
	double best = 1e9;
	int r;

	if (chdir("/tmp/df2717") != 0) { perror("chdir"); return 1; }
	for (r = 0; r < 3; r++) {
		double t0, t1;
		long i;
		int fd = open(path, O_RDWR | O_CREAT, 0666);
		if (fd < 0) { perror("create"); return 1; }
		close(fd);
		t0 = now();
		for (i = 0; i < n; i++) {
			fd = open(path, O_RDONLY);
			if (fd < 0) { perror("open"); return 1; }
			close(fd);
		}
		t1 = now();
		if (t1 - t0 < best) best = t1 - t0;
	}
	printf("bench: %ld relative opens, best %.3fs (%.0f ops/s, %.2f us/op)\n",
	       n, best, n / best, best * 1e6 / n);
	return 0;
}
