shell - nvidia-smi command in bash vs in terminal for maximum of an array -


overall goal: i'm trying assign python program gpu available memory.

current issue: when use command:

nvidia-smi --query-gpu=memory.free --format=csv

i following output:

memory.free [mib] 4800 mib 5332 mib 5346 mib 

of course, changes frequently, perhaps not best way accomplish overall goal. moment, i'm trying use figure out gpu in set of 3 has free memory. in case, it's gpu2 (they're labelled 0, 1, 2).

i created bash script:

#/bin/bash  myarr=( $(nvidia-smi --query-gpu=memory.free --format=csv) ) echo $myarr 

which outputs screen:

memory.free 

it used output in format:

memory.free [mib] 4800 mib 5332 mib 5346 mib 

i did (with first answer here):

myarr2=${myarr[2,4,6]} echo $myarr2 ic=(`tr ' ' '\n' <<<$myarr2 | cat -n | sort -k2,2nr | head -n1`) echo $ic ival=${ic[0]} cval=${ic[1]} echo $ival $cval 

however, doesn't seem matter do, index of maximum @ position 1. in example gave above, correct. in general, not correct.

the complete script:

#/bin/bash  myarr=( $(nvidia-smi --query-gpu=memory.free --format=csv) ) echo $myarr myarr2=${myarr[2,4,6]} echo $myarr2 ic=(`tr ' ' '\n' <<<$myarr2 | cat -n | sort -k2,2nr | head -n1`) echo $ic ival=${ic[0]} cval=${ic[1]} echo $ival $cval 

what wrong how i'm searching position of maximum?

the following verbose, careful follow practices; can't mislead surprising inputs process local filenames data (as happen if future version of software had *s in header, instance), , runs processing internal shell (which can slower large inputs, cases small amount of data being processed -- here -- faster on account of avoiding process startup overhead sort, tr, cat or other tools external shell).

#!/usr/bin/env bash  max_idx=0 max_mem=0 idx=0  {   read _;                         # discard first line (header)   while read -r mem _;         # each subsequent line, read first word mem     if (( mem > max_mem ));  # compare against maximum mem value seen       max_mem=$mem                # ...if greater, update both max value       max_idx=$idx                # ...and our stored index value.     fi     ((++idx))   done } < <(nvidia-smi --query-gpu=memory.free --format=csv)  echo "maximum memory seen $max_mem, @ processor $idx" 

if define nvidia-smi follows (note due - in name, definition isn't portable versions of bash):

nvidia-smi() { printf '%s\n' 'memory.free [mib]' '4800 mib' '5332 mib' '5346 mib'; } 

...this emits output:

maximum memory seen 5346, @ processor 3 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -