From: Andrew Lorimer Date: Tue, 16 Oct 2018 08:11:02 +0000 (+1100) Subject: more efficient formatting system for bandwidth.sh X-Git-Url: https://git.lorimer.id.au/scripts.git/diff_plain/0bf43baa2ea3593e443242c24b05db6e811fd5e8?hp=--cc more efficient formatting system for bandwidth.sh --- 0bf43baa2ea3593e443242c24b05db6e811fd5e8 diff --git a/i3blocks-bandwidth.sh b/i3blocks-bandwidth.sh index cab00a9..4c98e2f 100755 --- a/i3blocks-bandwidth.sh +++ b/i3blocks-bandwidth.sh @@ -83,45 +83,36 @@ tx_diff=$(( $tx - ${old[2]} )) rx_rate=$(( $rx_diff / $time_diff )) tx_rate=$(( $tx_diff / $time_diff )) +round() { + echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc)) +} + +format() { + if [ $1 == 0 ]; then + printf '000K' + elif [ $1 -lt 999 ]; then + # printf '%sK' "$1"; + printf %03d%s ${1%.*} K + elif [ $1 -lt 10240 ]; then + printf '%sM' "`echo "scale=1;$1 / 1024" | bc -l`" + elif [ $1 -lt 102400 ]; then + printf '0%sM' "$(round `echo "scale=1;$1 / 1024" | bc -l` 0)" + elif [ $1 -lt 1024000 ]; then + printf '%sM' "$(round `echo "scale=1;$1 / 1024" | bc -l` 0)" + else + printf '%sG' "$(round `echo "scale=2;$1 / 1048576" | bc -l` 1)" + fi +} + # shift by 10 bytes to get KiB/s. If the value is larger than # 1024^2 = 1048576, then display MiB/s instead # incoming echo -n "$INLABEL" -rx_kib=$(( $rx_rate >> 10 )) -if hash bc 2>/dev/null && [[ "$rx_rate" -gt 1048576 ]]; then - - if [ $rx_kib -lt 9900 ]; then - printf '%sM' "`echo "scale=1; $rx_kib / 1024" | bc`" - else - if [ $rx_kib -lt 1022976 ]; then - printf '%03dM' "`echo "scale=0; $rx_kib / 1024" | bc`" - else - printf "%sG" "`echo "scale=1; $rx_kib / 1024000" | bc`" - fi - fi -else - printf %03d ${rx_kib} # leading zeroes so length is constant - echo -n "K" -fi +format $(( $rx_rate >> 10 )) echo -n " " # outgoing echo -n "$OUTLABEL" -tx_kib=$(( $tx_rate >> 10 )) -if hash bc 2>/dev/null && [[ "$tx_rate" -gt 1048576 ]]; then - if [ $tx_kib -lt 9900 ]; then - printf '%sM' "`echo "scale=1; $tx_kib / 1024" | bc`" - else - if [ $tx_kib -lt 1022976 ]; then - printf '%03dM' "`echo "scale=0; $tx_kib / 1024" | bc`" - else - printf "%sG" "`echo "scale=1; $tx_kib / 1024000" | bc`" - fi - fi -else - printf %03d ${tx_kib} # leading zeroes so length is constant - echo -n "K" - -fi +format $(( $tx_rate >> 10 ))