t_fallocate.c 1.52 KB
// This program benchmarks fallocate on tmpfs
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/user.h>
#include <sys/mman.h>

// microtime returns current time as double
double microtime() {
	int err;
	struct timeval tv;

	err = gettimeofday(&tv, NULL);
	if (err == -1) {
		perror("gettimeofday");
		abort();
	}

	return tv.tv_sec + 1E-6 * tv.tv_usec;
}

int bench_tmpfs_fallocate(size_t xpagesize) {
	int fd, err, i;
	double Tstart, Tend;

	fd = open("/dev/shm/y.dat", O_RDWR | O_CREAT | O_TRUNC, 0666);
	if (fd == -1) {
		perror("open");
		abort();
	}

	size_t filesize = (3*1024*1024*1024ULL); // whole file size
	//size_t xpagesize = 1 * PAGE_SIZE;
	//size_t xpagesize = 512 * PAGE_SIZE;
	size_t niter = filesize / xpagesize;

	err = ftruncate(fd, filesize);
	if (err == -1) {
		perror("ftruncate");
		abort();
	}

	Tstart = microtime();
	for (i=0; i<niter; i++) {
		err = fallocate(fd, /*mode*/0, i*xpagesize, xpagesize);
		if (err == -1) {
			perror("fallocate");
			abort();
		}
	}
	Tend = microtime();

	printf("BenchmarkTmpfsFallocate/xpage=%ldK\t%ld\t%.3lf µs/op\t# t_total: %.3lfs\n",
			xpagesize / 1024, niter, (Tend - Tstart) * 1E6 / niter, (Tend - Tstart));

	err = close(fd);
	if (err == -1) {
		perror("close");
		abort();
	}

	return 0;
}


int main() {
	bench_tmpfs_fallocate(1*PAGE_SIZE);
	bench_tmpfs_fallocate(8*PAGE_SIZE);
	bench_tmpfs_fallocate(64*PAGE_SIZE);
	bench_tmpfs_fallocate(512*PAGE_SIZE);
}