qemu-vm/qemu-vm-cpus
2024-05-13 19:14:45 +02:00

117 lines
2.8 KiB
Bash
Executable file

#!/bin/sh
all_processors() {
grep -E '(processor|core id)' /proc/cpuinfo | while : ; do
read -r line0 || break
read -r line1 || break
if echo "$line0" | grep -q 'processor'; then
processor="$(echo "$line0" | sed -En 's/^[^0-9]*([0-9]+)$/\1/p')"
core="$(echo "$line1" | sed -En 's/^[^0-9]*([0-9]+)$/\1/p')"
elif echo "$line1" | grep -q 'processor'; then
processor="$(echo "$line1" | sed -En 's/^[^0-9]*([0-9]+)$/\1/p')"
core="$(echo "$line0" | sed -En 's/^[^0-9]*([0-9]+)$/\1/p')"
fi
echo "$processor $core"
done
}
take_host_processors() {
all_processors | sort -hk2 | head -n$1
}
take_vm_processors() {
all_processors | sort -hk2 | tail -n+$(($1+1))
}
_compress_seq_sub() {
first="$(echo "$@" | awk '{print $1}')"
last="$(echo "$@" | awk '{print $NF}')"
if [ $first = $last ]; then
printf '%s,' "$first"
else
printf '%s-%s,' "$first" "$last"
fi
}
_compress_seq() {
buffer=
while read -r item; do
if [ -z "$buffer" ]; then
buffer=$item
continue
fi
if [ $(($(echo "$buffer" | awk '{print $NF}')+1)) -eq $item ]; then
buffer="$buffer $item"
else
_compress_seq_sub $buffer
buffer=$item
fi
done
_compress_seq_sub $buffer
echo
}
compress_seq() {
_compress_seq | rev | cut -c2- | rev
}
_decompress_seq() {
(
IFS=,
for item in $@; do
if echo "$item" | grep -q '-'; then
num0="$(echo "$item" | awk -F- '{print $1}')"
num1="$(echo "$item" | awk -F- '{print $2}')"
printf '%s ' "$(seq $num0 $num1 | xargs echo)"
else
printf '%s ' $item
fi
done
echo
)
}
decompress_seq() {
_decompress_seq "$1" | rev | cut -c2- | rev
}
check_argument_is_number() {
if [ -z "$1" ]; then
echo "Error: must specify number of processors" >&2
return 1
fi
if [ "$1" -eq "$1" ] 2>/dev/null; then
true
else
echo "Error: provided argument '$1' is not a number" >&2
return 1
fi
}
compute_all() {
all_processors | sort -hk1 | awk '{print $1}' | compress_seq
}
compute_host() {
if ! check_argument_is_number $1; then
return $?
fi
take_host_processors $1 | sort -hk1 | awk '{print $1}' | \
compress_seq
}
compute_vm() {
if ! check_argument_is_number $1; then
return $?
fi
take_vm_processors $1 | sort -hk1 | awk '{print $1}' | \
compress_seq
}
processors_per_core() {
processor_count=$(all_processors | awk '{print $1}' | sort -h | uniq | wc -l)
core_count=$(all_processors | awk '{print $2}' | sort -h | uniq | wc -l)
echo $((processor_count/core_count))
}
"$@"