windows - Windows 批处理文件中的计时器

标签 windows batch-file time timer cmd

有人能告诉我一种将计时器添加到 Windows 批处理文件的方法吗?我需要跟踪我的批处理从开始运行的时间。

最佳答案

重构代码以计算耗时:

  • 减少计算代码,
  • 为少于 0.1 秒的耗时提供填充,
  • 使用标签允许多次调用它,并对定时器代码进行分组。

可重用代码:

: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

调用代码:

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

请注意“1”前缀以避免将零填充值解释为八进制值(08 和 09)的错误,并使用适当的常量进行更正。由于这可能会混淆理解核心计算,因此单行 for 语句的替代方法如下所示:

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

关于windows - Windows 批处理文件中的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4313897/

相关文章:

android - 移动设备之间的统一用户界面

c++ - 如何在 Windows 上的 C++ 中管理文件/目录的发现和使用?

batch-file - 在批处理文件中使用 endlocal 设置变量,但这些变量在 setlocal/endlocal block 之外永远不可用

php - 这个时间格式是什么?

python-3.x - python |以时间间隔从网络摄像头捕获图像

c++ - cmake 在 Windows 上生成错误,因为它使用\as escape seq

windows - Vagrant Windows - ssh_exchange_identification : read: Connection reset by peer

batch-file - 批量强制关闭窗口

windows - Apache Ant : Terminate process started by <exec> when ant process is terminated

r - 结合 POSIXct 给出错误的时间