简体   繁体   中英

how to implement StopClock in BatchFile?

I would like to measure the time taken for multiple applications which are invoked in a batchfile (with some conditions). Can you please let know how to implement a StopClock in a BatchFile. We've a StopClock class in C# and C++.

Thanks in advance.

Here is a batch file I put together to measure the time taken for 2 applications (in this it's notepad and rdp ) to run until they are closed in seconds.

@echo off
set stime=0
start notepad.exe
start mstsc.exe
set /a stime+=1

:LOOP
timeout /t 1 >nul
set /a stime+=1
tasklist /nh /fi "imagename eq notepad.exe" | find /i "notepad.exe" >nul && goto :LOOP || goto :LOOP2

:LOOP2
timeout /t 1 >nul
set /a stime+=1
tasklist /nh /fi "imagename eq mstsc.exe" | find /i "mstsc.exe" >nul && goto :LOOP2 || goto :BREAK

:BREAK
echo Time taken = %stime%
pause >nul

It's not really accurate like the C# StopWatch and the like classes but it is quite close. Just have a play around with the times until you get it close enough.

Just copy the loop sections (and increment the label ie :LOOP3 , :LOOP4 ) for each app that you want to run and replace the filenames accordingly.

Hope this helps

You can capture the start and stop time in variables by setting a variable to %TIME% .

FOR /F can be used to parse the time into hours, minutes, seconds, and centiseconds (1/100 second).

SET /A treates numbers with leading 0 as octal, so each number must be prefixed with 1 to force decimal notation. Everything else is relatively straight forward math.

The :timeDiff routine can measure any elapsed time that is less than 24 hours. The result is in centiseconds (1/100 second).

@echo off
setlocal

:: Measure the time to do something
set start=%time%
for /l %%N in (1 1 100000) do echo off
set stop=%time%

:: Echo the elapsed time
call :timeDiff start stop

:: Store the elapsed time in variable named result
call :timeDiff start stop result
echo result=%result%

exit /b


:timeDiff  StartVar  StopVar  [RtnVar]
::
:: Compute elapsed time between time stored in StartVar and StopVar.
::
:: Return result in RtnVar, or echo result if RtnVar not specified
::
:: Result is in units of csec (1/100 second)
::
setlocal enableDelayedExpansion
for /f "tokens=1-4 delims=:.," %%A in ("!%~1!") do set /a timeDiff.start=(1%%A*360000)+(1%%B*6000)+1%%C%%D-36610000
for /f "tokens=1-4 delims=:.," %%A in ("!%~2!") do set /a timeDiff.stop=(1%%A*360000)+(1%%B*6000)+1%%C%%D-36610000
set /a rtn=timeDiff.stop-timeDiff.start
if rtn lss 0 set /a rtn+=864000
( endlocal
  if "%~3" neq "" (set %~3=%rtn%) else echo %rtn%
)
exit /b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM