#!/usr/bin/env bash

if [ -f a.out ]
then
  echo "Found file a.out, will not overwrite" >&2
  exit 1
fi

gccflags='-g -march=native'
perfflags='--timeout 120000 -x, '\
'-e cycles:u -e instructions:u -e duration_time:u'

inputs='../input_qualification_round_2019/[acfghij]_*.txt'

function compile_measure () {
  # $1 ... C file
  # $2 ... GCC options
  # $3 ... log file name

  echo "gcc $2 $1" | tee -a "$3"
  gcc $gccflags $2 -o a.out "$1"

  for infile in $inputs
  do
    echo "$1,$infile"
    echo -n "$1,$infile," >>"$3"

    perf stat $perfflags --output stat-tmp.log \
      ./a.out "$infile" 1>/dev/null 2>>stat-dbgs.log

    sed -ne '/^[0-9]/p' stat-tmp.log | cut -d, -f1 \
      | sed -ze 's/\n\(.\)/,\1/g' >>"$3"
  done
}

uname -p >stat-dbgs.log
gcc --version >>stat-dbgs.log

for cfile in solv.c solv2.c solv3.c
do
  echo "== $cfile =="
  compile_measure "$cfile" '-O1 -DDEBUG'     stat-o1-dbg.log
  compile_measure "$cfile" '-O1'             stat-o1.log
  compile_measure "$cfile" '-Ofast -DDEBUG'  stat-of-dbg.log
  compile_measure "$cfile" '-Ofast'          stat-of.log
  compile_measure "$cfile" '-Ofast -DNDEBUG' stat-of-ndbg.log
done

rm a.out stat-tmp.log
