4

I am trying to write a batch file that takes the time taken of a command and converts it into hours, minutes and seconds.

Here's what I've got:

@echo off

set /a sec=0
set /a min=0
set /a hrs=0
for /f %%G in ('ping localhost -n 100 >nul') do (
    ping localhost -n 1 >nul
    set /a sec+=1
    if %sec%==60 ( 
        set /a min+=1
        set /a sec=0
    )
    if %min%==60 (
        set /a hrs+=1
        set /a min=0
    ) 
)
echo Time taken: %hrs%:%min%:%sec%.

I keep getting a ") was unexpected at this time." error. The FOR loop definitely works and it is just the IF statements that are the problem.

I have tried using the EQU operator and adding quotation marks to no avail. Could anybody help?

Also, I read somewhere that the set operator may not work under an IF statement - is this true?

1 Answers1

2

Your syntax error is the result of your unescaped redirection within the FOR IN() clause. The following will eliminate the syntax error:

for /f %%G in ('ping localhost -n 100 ^>nul') do (

But your script seems utterly useless. Redirecting the IN() clause PING to null means there is nothing to iterate, so the code within the loop will never fire. Even if you remove the redirection, it will be highly inaccurate.

Better to get the %TIME% at the start and end of the process, and use relatively simple parsing and math to get the elapsed time down to 1/100 seconds. This can process times up to ~24 hours.

@echo off
setlocal
set "t1=%time%"
rem someCommandThatYouWantToTime
set "t2=%time%"

:: Compute elapsed time as 1/100 seconds
for /f "tokens=1-4 delims=:.," %%a in ("%t1: =0%") do set /a "t1=(((1%%a*60)+1%%b)*60+1%%c)*100+1%%d-36610100"
for /f "tokens=1-4 delims=:.," %%a in ("%t2: =0%") do set /a "t2=(((1%%a*60)+1%%b)*60+1%%c)*100+1%%d-36610100, tDiff=t2-t1"
if %tDiff% lss 0 set /a tDiff+=24*60*60*100

echo Elapsed time = %tDiff% centiseconds

:: Convert centiseconds into hours, minutes, decimal seconds
set /a "f=tDiff%%100, s=(tDiff/100)%%60, m=(tDiff/100/60)%%60, h=tDiff/100/60/60"
if %f% lss 10 set "f=0%f%"
if %s% lss 10 set "s=0%s%"
if %m% lss 10 set "m=0%m%"
if %h% lss 10 set "h=0%h%"

echo Elapsed time = %h%:%m%:%s%.%f%
dbenham
  • 11,194
  • 6
  • 30
  • 47