pbiering / ipv6calc

ipv6calc
https://www.deepspace6.net/projects/ipv6calc.html
Other
45 stars 15 forks source link

Shell scripts refinement #20

Closed grayed closed 3 years ago

grayed commented 3 years ago

Mostly minor tweaks:

N.B.: It's easier to review this PR commit-by-commit, not as a whole thing.

pbiering commented 3 years ago

btw: there is one disadvantage of the use of true/false: it's roundabout 3% slower...

grayed commented 3 years ago

btw: there is one disadvantage of the use of true/false: it's roundabout 3% slower...

Hm. Likely it depends on a shell and OS. On my system things are reversed. I wrote two scripts and checked which one would work faster:

bool.sh

n=$1

a=true
b=false

while [ $n -gt 0 ]; do
        n=$(($n - 1))
        if $a; then
                foo=bar
        fi
        if $b; then
                qwe=rty
        fi
done

vars.sh

n=$1

a=1
b=0

while [ $n -gt 0 ]; do
        n=$(($n - 1))
        if [ "$a" = "1" ]; then
                foo=bar
        fi
        if [ "$b" = "1" ]; then
                qwe=rty
        fi
done

Results

Time in seconds. Note: 'ksh' is OpenBSD ksh, while ksh93 is installed from ports.

$ sh run.sh 10 10000 bool.sh vars.sh
bash    bool.sh user=0.280000   sys=0.004000    total=0.284000
bash    vars.sh user=0.399000   sys=0.003000    total=0.402000
dash    bool.sh user=0.160000   sys=0.131000    total=0.291000
dash    vars.sh user=0.287000   sys=0.212000    total=0.499000
ksh     bool.sh user=0.120000   sys=0.000000    total=0.120000
ksh     vars.sh user=0.153000   sys=0.001000    total=0.154000
ksh93   bool.sh user=0.047000   sys=0.004000    total=0.051000
ksh93   vars.sh user=0.045000   sys=0.002000    total=0.047000
zsh     bool.sh user=0.155000   sys=0.032000    total=0.187000
zsh     vars.sh user=0.196000   sys=0.030000    total=0.226000

The check script itself:

#!/bin/sh

set -u

ntries=$1; shift
ncycles=$1; shift

shells="bash dash ksh ksh93 zsh"
time=$(command -v time)

for sh in $shells; do
        # do the cold start
        echo "false || true" | $time $sh 2>/dev/null

        for s in "$@"; do
                usrall=0
                sysall=0
                for i in `jot $ntries`; do
                        t=$($time -p $sh $s $ncycles 2>&1)
                        usr=$(echo "$t" | awk '/^user/{print $2}')
                        sys=$(echo "$t" | awk '/^sys/{print $2}')
                        usrall=$(echo "${usrall}+${usr}" | bc)
                        sysall=$(echo "${sysall}+${sys}" | bc)
                done
                usravg=$(echo "${usrall}/${ntries}" | bc -l)
                sysavg=$(echo "${sysall}/${ntries}" | bc -l)
                total=$(echo "${usravg}+${sysavg}" | bc -l)
                printf "%s\t%s\tuser=%f\tsys=%f\ttotal=%f\n" \
                       "$sh" "$s" $usravg $sysavg $total
        done
done