Can someone point me to a way of adding a timer to a Windows batch file? I need to track the time my batch runs from start.
Timeout with the parameter /NOBREAK If we take the example from before and run that in a BATCH file: timeout /t 60 then while waiting those 60 seconds, you are actually able to break the timeout by pressing any key on your keyboard. To prevent this we simply add the parameter /NOBREAK to the end of it.
You can insert the pause command before a section of the batch file that you might not want to process. When pause suspends processing of the batch program, you can press CTRL+C and then press Y to stop the batch program.
You can use timeout command to wait for command prompt or batch script for the specified amount of time. The time is defined in Seconds. The above commands will break the timeout process on pressing any key. You can use /NOBREAK ignore key presses and wait for the specified time.
Refactored the code to calculate the elapsed time:
Reusable code:
:StartTimer
:: Store start time
set StartTIME=%TIME%
for /f "usebackq tokens=1-4 delims=:., " %%f in (`echo %StartTIME: =0%`) do set /a Start100S=1%%f*360000+1%%g*6000+1%%h*100+1%%i-36610100
goto :EOF
:StopTimer
:: Get the end time
set StopTIME=%TIME%
for /f "usebackq tokens=1-4 delims=:., " %%f in (`echo %StopTIME: =0%`) do set /a Stop100S=1%%f*360000+1%%g*6000+1%%h*100+1%%i-36610100
:: Test midnight rollover. If so, add 1 day=8640000 1/100ths secs
if %Stop100S% LSS %Start100S% set /a Stop100S+=8640000
set /a TookTime=%Stop100S%-%Start100S%
set TookTimePadded=0%TookTime%
goto :EOF
:DisplayTimerResult
:: Show timer start/stop/delta
echo Started: %StartTime%
echo Stopped: %StopTime%
echo Elapsed: %TookTime:~0,-2%.%TookTimePadded:~-2% seconds
goto :EOF
Calling code:
call :StartTimer
::
:: Add your script functionality here
::
call :StopTimer
call :DisplayTimerResult
pause
call :StartTimer
::
:: Add more script functionality here
::
call :StopTimer
call :DisplayTimerResult
goto :EOF
Note the "1"-prefix to avoid interpretation errors of zero-padded values as octal values (08 and 09), and the correction with the appropriate constant. As this might be confusing to understand the core calculation, an alternative to the one-line for
statement would be something like the following:
for /f "usebackq tokens=1-4 delims=:., " %%f in (`echo.%StartTIME%`) do set TempTIME=%%f %%g %%h %%i
for /f "usebackq tokens=1-4" %%f in (`echo %TempTIME: 0= %`) do set /a Start100S=%%f*360000+%%g*6000+%%h*100+%%i
A minimalistic version with elapsed time in seconds.
@set /A _tic=%time:~0,2%*3600^
+%time:~3,1%*10*60^
+%time:~4,1%*60^
+%time:~6,1%*10^
+%time:~7,1% >nul
:: actual script
@set /A _toc=%time:~0,2%*3600^
+%time:~3,1%*10*60^
+%time:~4,1%*60^
+%time:~6,1%*10^
+%time:~7,1% >nul
@set /A _elapsed=%_toc%-%_tic
@echo %_elapsed% seconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With