/ scripts / gpu_usage.sh
gpu_usage.sh
 1  #!/usr/bin/env bash
 2  # setting the locale, some users have issues with different locales, this forces the correct one
 3  export LC_ALL=en_US.UTF-8
 4  
 5  current_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
 6  source $current_dir/utils.sh
 7  
 8  get_platform()
 9  {
10    case $(uname -s) in
11      Linux)
12        # use this option for when your gpu isn't detected
13        gpu_label=$(get_tmux_option "@dracula-force-gpu" false)
14        if [[ "$gpu_label" != false ]]; then
15          echo $gpu_label
16        else
17          # attempt to detect the gpu
18          gpu=$(lspci -v | grep VGA | head -n 1 | awk '{print $5}')
19          if [[ -n $gpu ]]; then
20            # if a gpu is detected, return it
21            echo $gpu
22          elif type -a nvidia-smi >> /dev/null; then
23            # if no gpu was detected, and nvidia-smi is installed, we'll still try nvidia
24            echo "NVIDIA"
25          fi
26        fi
27        ;;
28  
29      Darwin)
30        # WARNING: for this to work the powermetrics command needs to be run without password
31        #   add this to the sudoers file, replacing the username and omitting the quotes.
32        #   be mindful of the tabs: "username		ALL = (root) NOPASSWD: /usr/bin/powermetrics"
33        echo "apple"
34        ;;
35  
36      CYGWIN*|MINGW32*|MSYS*|MINGW*)
37        # TODO - windows compatability
38        ;;
39    esac
40  }
41  
42  get_gpu()
43  {
44    gpu=$(get_platform)
45    if [[ "$gpu" == NVIDIA ]]; then
46      usage=$(nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits | awk '{ sum += $0 } END { printf("%d%%\n", sum / NR) }')
47    elif [[ "$gpu" == apple ]]; then
48      usage="$(sudo powermetrics --samplers gpu_power -i500 -n 1 | grep 'active residency' | sed 's/[^0-9.%]//g' | sed 's/[%].*$//g')%"
49    else
50      usage='unknown'
51    fi
52    normalize_percent_len $usage
53  }
54  
55  main()
56  {
57    # storing the refresh rate in the variable RATE, default is 5
58    RATE=$(get_tmux_option "@dracula-refresh-rate" 5)
59    gpu_label=$(get_tmux_option "@dracula-gpu-usage-label" "GPU")
60    gpu_usage=$(get_gpu)
61    echo "$gpu_label $gpu_usage"
62    sleep $RATE
63  }
64  
65  # run the main driver
66  main