Jozo
Jozo

Reputation: 115

Assign a value derrived from a cmd command to a bat variable

I'm new to batch scripting and have encountered an issue. I am running a command to get the GPU utilization, and I want to substring it so that I can use the utilization as a integer.

Running nvidia-smi -q -d UTILIZATION gives me this output:

GPU 00000000:01:00.0
    Utilization
        Gpu                         : 100 %
        Memory                      : 0 %
        Encoder                     : 0 %
        Decoder                     : 0 %

Here is the relevant bat part:

:checkGPUUtil
cd nvsmiPath
goto :loop
timeout 1
goto :start

:loop

if %tries% leq 3 (
    set /a tries +=1
    sleep 10
    goto :loop
)

So what I am looking for is to copy the value shown in the GPU column, which is currently 100 and assign it to an integer.

How can I achieve this?

Upvotes: 0

Views: 121

Answers (1)

Magoo
Magoo

Reputation: 79983

for %%a in (gpu1 gpu2) do set "%%a="
for /f "tokens=1,2delims=: " %%a in ('nvidia-smi -q -d UTILIZATION'
 ) do if "%%a"=="Gpu" if defined gpu1 (set /a gpu2=%%b) else (set /a gpu1=%%b)

echo GPU : %gpu1% and %gpu2%
set gpu

Execute the command (in single quotes) tokenising on : and Space, selecing the first and second tokens. If the first token exactly matches Gpu then assign the second token to the variable.

See for /f from the prompt (or examples here on SO) for documentation.

[modified for 2 gpus - mentioning this info in the original question would have made the task easier.]

Upvotes: 1

Related Questions