Lynx Lynx - 2 months ago 7x
Linux Question

Which one is more efficient for float operations, awk or bc?

I am writing a system performance script in bash. I want to compute the CPU usage in terms of percent. I have two implementations, one using awk and another one using bc. I would like to know which of the two versions is more efficient. Is it better to use awk or bc for float computations? Thanks!

Version #1 (Using bc)

CPU=$(mpstat 1 1 | grep "Average" | awk '{print $11}')
CPU=$(echo "scale=2;(100-$CPU)" | bc -l)
echo $CPU

Version #2 (Using awk)

CPU=$(mpstat 1 1 | grep "Average" | awk '{idle = $11} {print 100 - idle}')
echo $CPU

Mat Mat

Since the processing time of both is going to be tiny, the version that spawns the least amount of processes and subshells is going to be "more efficient".

That's your second example.

But you can make it even simpler by eliminating the grep:

CPU=$(mpstat 1 1 | awk '/Average/{print 100 - $11}')