bash - Is this the faster way to test cpu load using shell scripting? -
i'm relatively new shell scripting , i'm in process of writing own health checking scripts using bash.
is following script test cpu load best can have in terms of performance, readability , maintainability?
#!/bin/sh getloadavg5 () { echo $(cat /proc/loadavg | cut -f2 -d' ') } getnumcpus () { echo $(cat /proc/cpuinfo | grep '^processor' | wc -l) } awk \ -v failthold=0.8 \ -v warnthold=0.7 \ -v loadavg=$(getloadavg5) \ -v numcpus=$(getnumcpus) \ 'begin { ratio=loadavg/numcpus if (ratio >= failthold) exit 2 if (ratio >= warnthold) exit 1 exit 0 }'
this might more suitable code review stackexchange, without condoning use of load averages in way, here ideas:
#!/bin/sh read -r 1 5 fifteen rest < /proc/loadavg cpus=$(grep -c '^processor' /proc/cpuinfo) awk \ -v failthold=0.8 \ -v warnthold=0.7 \ -v loadavg="$five" \ -v numcpus="$cpus" \ 'begin { ratio=loadavg/numcpus if (ratio >= failthold) exit 2 if (ratio >= warnthold) exit 1 exit 0 }'
it doesn't have of unnecessary cats/echos.
it happens run faster forking 1 or 2 times (depending on shell) instead of ~10, if performance issue shell scripts should avoided in general.
Comments
Post a Comment