#!/bin/sh

set -e

DEBUG=true
NUM_RUN=10
CSV_FILE=lmbench.csv

drop_caches()
{
	sync
	echo 3 > /proc/sys/vm/drop_caches
}

run_iter()
{
	local sum=0

	for i in $(seq $NUM_RUN); do
		drop_caches

		num=$(eval "$@")
		$DEBUG && echo $num >&2
		sum=$(echo "scale=4; $num + $sum" | bc)
	done

	echo "scale=4; $sum / $NUM_RUN" | bc
}

[ -n "$1" ] && CSV_FILE="$1"

#
# Floating Point Multiplication (lat_ops)
#
average=$(run_iter 'lat_ops 2>&1 | grep "^float mul:" | cut -f3 -d" "')
echo "Floating Point Multiplication (lat_ops) : $average nanosecs"
echo "lat_ops,Floating Point Multiplication,time in nanosecs,$average" >> $CSV_FILE

#
# Memory Bandwidth (bw_mem)
#
average=$(run_iter 'bw_mem 33554432 rdwr 2>&1 | cut -d" " -f2')
echo "Memory Bandwidth (bw_mem)               : $average MB/sec"
echo "bw_mem,Memory Bandwidth,Troughtput in MB/sec,$average" >> $CSV_FILE

#
# Context Switching Time (lat_ctx)
#
average=$(run_iter 'string_no_newline=$(lat_ctx -s 8 16 2>&1); echo $string_no_newline | cut -d" " -f4')
echo "Context Switching Time (lat_ctx)        : $average microsecs"
echo "lat_ctx,Context Switching Time,time in microsecs,$average" >> $CSV_FILE

#
# Syscall Performance (lat_syscall)
#
tmpfile=$(mktemp)
touch $tmpfile
average=$(run_iter 'lat_syscall open $tmpfile 2>&1 | sed -e "s;^Simple open/close: \(.*\) microseconds$;\1;"')
rm $tmpfile
echo "Syscall Performance (lat_syscall)       : $average microsecs"
echo "lat_syscall,Syscall Performance,time in microsecs,$average" >> $CSV_FILE

#
# Process Forking (lat_proc)
#
average=$(run_iter 'lat_proc fork 2>&1 | sed -e "s;^Process fork+exit: \(.*\) microseconds$;\1;"')
echo "Process Forking (lat_proc)              : $average microsecs"
echo "lat_proc,Process Forking,time in usecs,$average" >> $CSV_FILE
