#!/bin/bash

if [ $UID != 0 ]; then
	echo "Must be root."
	exit 0
fi

ram_size=$(free -mto | grep Mem: | awk '{ print $2 }')
medium_file_size=$(($ram_size / 3))
large_file_size=$(($ram_size * 4))

if [ ! -e "/tmp/medium_file" ] || [ ! -e "/tmp/large_file" ]; then
	echo "Creating test files..."
	dd if=/dev/zero of=/tmp/medium_file bs=1M count=$medium_file_size
	dd if=/dev/zero of=/tmp/large_file bs=1M count=$large_file_size
	echo
fi

TIMEFORMAT=' %3lR'

echo "Base test:"
echo

sync; echo 1 >/proc/sys/vm/drop_caches

echo -n "1st run:"
time ./working_set_simul /tmp/medium_file
echo -n "2nd run:"
time ./working_set_simul /tmp/medium_file
echo -n "3rd run:"
time ./working_set_simul /tmp/medium_file
echo -n "4th run:"
time ./working_set_simul /tmp/medium_file
echo

echo "Reading a large file test:"
echo

sync; echo 1 >/proc/sys/vm/drop_caches

echo -n "1st run:"
time ./working_set_simul /tmp/medium_file
echo -n "2nd run:"
time ./working_set_simul /tmp/medium_file
cp -v /tmp/large_file /dev/null
echo -n "3rd run:"
time ./working_set_simul /tmp/medium_file
echo -n "4th run:"
time ./working_set_simul /tmp/medium_file
echo

echo "Copying (using cp) a large file test:"
echo

sync; echo 1 >/proc/sys/vm/drop_caches

echo -n "1st run:"
time ./working_set_simul /tmp/medium_file
echo -n "2nd run:"
time ./working_set_simul /tmp/medium_file
cp -v /tmp/large_file /tmp/large_file.copy
echo -n "3rd run:"
time ./working_set_simul /tmp/medium_file
echo -n "4th run:"
time ./working_set_simul /tmp/medium_file
rm /tmp/large_file.copy
echo

echo "Copying (using fadvise_cp) a large file test:"
echo

sync; echo 1 >/proc/sys/vm/drop_caches

echo -n "1st run:"
time ./working_set_simul /tmp/medium_file
echo -n "2nd run:"
time ./working_set_simul /tmp/medium_file
echo "Copying large file..."
./fadvise_cp /tmp/large_file /tmp/large_file.copy
echo -n "3rd run:"
time ./working_set_simul /tmp/medium_file
echo -n "4th run:"
time ./working_set_simul /tmp/medium_file
rm /tmp/large_file.copy
echo

echo "Copying (using splice-cp) a large file test:"
echo

sync; echo 1 >/proc/sys/vm/drop_caches

echo -n "1st run:"
time ./working_set_simul /tmp/medium_file
echo -n "2nd run:"
time ./working_set_simul /tmp/medium_file
echo "Copying large file..."
splice-cp /tmp/large_file /tmp/large_file.copy
echo -n "3rd run:"
time ./working_set_simul /tmp/medium_file
echo -n "4th run:"
time ./working_set_simul /tmp/medium_file
rm /tmp/large_file.copy
echo

echo "Copying (using rsync) a large file test:"
echo

sync; echo 1 >/proc/sys/vm/drop_caches

echo -n "1st run:"
time ./working_set_simul /tmp/medium_file
echo -n "2nd run:"
time ./working_set_simul /tmp/medium_file
rsync -cv /tmp/large_file /tmp/large_file.copy
echo -n "3rd run:"
time ./working_set_simul /tmp/medium_file
echo -n "4th run:"
time ./working_set_simul /tmp/medium_file
rm /tmp/large_file.copy
echo

exit 0

