#!/bin/bash

NAME=$1

if [ ! -f "raw/${NAME}.out" ]; then
    echo "Not output for ${NAME}"
    exit 1
fi

if [ ! -f "raw/${NAME}.data" ]; then
    echo "Not perf record for ${NAME}"
    exit 1
fi

echo "Processing perf data for ${NAME}"

OPS=$(grep -e 'Total ops' raw/${NAME}.out)
CPOP=$( echo "Hello $OPS" | \grep -oP ", \K[0-9,]+(?=o)" --color | tr -d ',')
CPUSH=$(echo "Hello $OPS" | \grep -oP "\(\K[0-9,]+(?=i)" --color | tr -d ',')

REPORT=''
perf report -n --percent-limit 5 --stdio --no-children -i raw/${NAME}.data > raw/.temp
EVENT=$(cat raw/.temp | grep -e '^# Samples'| cut -d ' ' -f 6)
SPOP=$( cat raw/.temp | grep -e '] relaxed_list<Node>::pop'  | tr -s ' ' | cut -d ' ' -f 3)
SPUSH=$(cat raw/.temp | grep -e '] relaxed_list<Node>::push' | tr -s ' ' | cut -d ' ' -f 3)
SARR=$( cat raw/.temp | grep -e '] snz[i|m]_t::node::arrive_h'   | tr -s ' ' | cut -d ' ' -f 3)

echo "$OPS"
echo "Push count: $CPUSH"
echo "Pop  count: $CPOP"

echo "Pop    samples: $SPOP"
echo "Push   samples: $SPUSH"
echo "Arrive samples: $SARR"

SpPUSH=$(bc -l <<< "scale=9; $SPUSH / $CPUSH")
SpPOP=$( bc -l <<< "scale=9; $SPOP  / $CPOP" )
SpARR=$( bc -l <<< "scale=9; $SARR  / $CPUSH")

printf "%s per push()  : %.9f\n" $EVENT $SpPUSH | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta'
printf "%s per pop()   : %.9f\n" $EVENT $SpPOP  | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta'
printf "%s per arrive(): %.9f\n" $EVENT $SpARR  | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta'