0

I am trying to find the average CPU utilization of my android application using the code below

#!/bin/bash
counter=1
while [ $counter -le 10 ]
    do
        current_cpu=$(adb shell top -n 1 | grep org.carleton.iot.mobile_cep | awk '{print $5}' | sed 's|%||g')
        echo "current_cpu = "$current_cpu
        total_cpu=$((total_cpu + current_cpu))
        echo "total_cpu = "$total_cpu
        echo "counter = "$counter
        average_cpu=$(((totalMemory / counter)))
        echo "average_cpu = "$average_cpu
        echo "\n"
        ((counter++))

        sleep 1
    done
echo  done

It gives the following results

current_cpu = 7
total_cpu = 7
counter = 1
average_cpu = 0

current_cpu = 8
total_cpu = 15
counter = 2
average_cpu = 0


current_cpu = 6
total_cpu = 21
counter = 3
average_cpu = 0

current_cpu = 8
total_cpu = 29
counter = 4
average_cpu = 0

However, the value of average_cpu should be equal to total_cpu/counter value.

ruakh
  • 175,680
  • 26
  • 273
  • 307
Amarjit Dhillon
  • 2,718
  • 3
  • 23
  • 62
  • 2
    It's a simple typo: `$(((totalMemory / counter)))` is zero because `totalMemory` is not set. (You meant to write `total_cpu` instead.) That said, you should follow Andrea Corbellini's link to learn about better approaches. – ruakh Apr 29 '18 at 02:08
  • @ruakh : omg, my bad. you are right boss – Amarjit Dhillon Apr 29 '18 at 02:11
  • And `bc <<< 'scale=2; total_cpu/counter'` does not work because you forgot to expand the variables: `bc <<< "scale=2; $total_cpu/$counter"` – Andrea Corbellini Apr 29 '18 at 02:14
  • Just for kicks, `echo "totalMemory: $totalMemory"` before `average_cpu=$(((totalMemory / counter)))` to verify it actually contains what you think it does. – David C. Rankin Apr 29 '18 at 02:19

1 Answers1

1

Bash division don't work when result is not integer, you have use scale and bc as

echo "scale=2 ; $totalmemory / $counter" | bc

Here value of scale is the precision like if it's 2, it'll return values upto 2 places after decimal point like .55

Mesar ali
  • 1,832
  • 2
  • 16
  • 18