bashshellaveragenvidia

Calculate the Average of Numbers from command output


Need help with a nvidia-smi command. When i run the following command:

nvidia-smi --format=csv --query-gpu=utilization.gpu

It returns:

utilization.gpu [%]
89 % 
45 %
22 %
68 %

I want to have a script that uses these returned values and calculate an average number. So it should do this 89 + 45 + 22 + 68 = 224 / 4 = 56

Is there a way of doing this ?


Solution

  • nvidia-smi --format=csv --query-gpu=utilization.gpu | awk '/[[:digit:]]+[[:space:]]%/ { tot+=$1;cnt++ } END { print tot/cnt }'
    

    Pipe the output of nvidia-smi ... to awk. Process lines that have a one or more digits, a space and then a "%". Create a running total (tot) and also, count the number of occurrences (cnt) At the end, divide tot by cnt and print the result.