#!/bin/bash
#
# Simple scheduler test for deeper idle states (CPU idle).
# Test runs some tasks and let scheduler decide where they
# are executed.
# At the end it prints CPU idle statistics.
#

SCHED_TASKS=2
ROUNDS=10
if [ $# -ne 2 ]; then
	echo "Usage: $(basename $0) <# of tasks> <# executions>"
	exit 1
elif [ $# -eq 2 ]; then
	SCHED_TASKS=$1
	ROUNDS=$2
fi

CPU_IDLE_DIR="/sys/devices/system/cpu/cpu[0-9]*/cpuidle"
CPI_IDLE_STATE="state1"
SCHED_TPERIOD=50000
SCHED_WORK=100
SCHED_COUNT=100

echo "Found $(ls -d1 ${CPU_IDLE_DIR} | wc -l) CPU idle sysfs entries"
echo "Important: This will extract only $CPI_IDLE_STATE idle time"
echo "Spawning $SCHED_TASKS tasks"

before=$(cat ${CPU_IDLE_DIR}/${CPI_IDLE_STATE}/time)
#echo "Before: $before"

for i in `seq $ROUNDS` ; do
	offset=100
	pids=
	for i in `seq $SCHED_TASKS` ; do
		echo "./sched_task --tperiod $SCHED_TPERIOD --work $SCHED_WORK --offset $offset --count $SCHED_COUNT &"
		./sched_task --sched_other --tperiod $SCHED_TPERIOD --work $SCHED_WORK --offset $offset --count $SCHED_COUNT &
		pids="$pids $!"
		offset=$((offset+3300));
	done
	wait $pids
	sleep 5
done

after=$(cat ${CPU_IDLE_DIR}/${CPI_IDLE_STATE}/time)
#echo "After: $after"

echo "Diff:"
i=1
for cpu_before in $before ; do
	cpu_after=$(echo $after | cut -f $i -d ' ')
	echo $((cpu_after-cpu_before));
	i=$((i+1))
done

