### 如何在批处理文件中实现StopWatch？

#### 2 个答案:

``````@echo off
set stime=0
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
``````

FOR / F可用于将时间分析为小时，分钟，秒和厘秒（1/100秒）。

SET / A处理前导0为八进制的数字，因此每个数字必须以1为前缀以强制使用十进制表示法。其他一切都是相对直接的数学。

`:timeDiff`例程可以测量任何小于24小时的经过时间。结果是以厘秒为单位（1/100秒）。

``````@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
``````