#!/bin/bash

if [[ $EUID -ne 0 ]]; then
    echo "Run as root, please"
    exit 1
fi

# Start recording
perf record -a -e kvm:\* -e sched:sched_process_exec &
pid_perf=$!

sleep 1

# Run whatever (THIS IS PAINFULLY UNSECURE!)
$@ &
pid_qemu=$!

# Sleep some time
sleep 2

# Stop recording
kill -SIGINT $pid_perf

# Wait to write
sleep 2

# Stop QEMU
kill -SIGINT $pid_qemu

# Get & process results
echo
echo

t0=`perf script | grep "sched:sched_process_exec" | grep "qemu-system-x86" | awk '{print $4}'`
t1=`perf script | grep "kvm:kvm_entry" | head -1 | awk '{print $4}'`
t11=`perf script | grep "pio_write at 0xf5" | tail -1 | awk '{print $4}'`
t2=`perf script | grep "pio_write at 0xf4" | tail -1 | awk '{print $4}'`

if [[ -z "$t0" ]]; then
    echo "QEMU start time is empty"
    exit 1
fi

if [[ -z "$t1" ]]; then
    echo "QEMU startup end time is empty"
    exit 1
fi


if [[ -z "$t11" ]]; then
    echo "BIOS time is empty"
    exit 1
fi

t0=${t0::-1}
t1=${t1::-1}
t11=${t11::-1}

if [[ -z "$t2" ]]; then
    echo "Kernel boot time is empty"
else
    t2=${t2::-1}
fi

# Print results
echo -n "QEMU startup time: "
echo "$t1 - $t0" | bc

echo -n "BIOS startup time: "
echo "$t11 - $t1" | bc

if [[ -n "$t2" ]]; then
    echo -n "Kernel setup time: "
    echo "$t2 - $t11" | bc
    echo -n "Total time: "
    echo "$t2 - $t0" | bc
else
    echo -n "Total time: "
    echo "$t11 - $t0" | bc
fi


