我目前正在开发一个批处理文件,自动编译并执行源文件并显示执行时间。我只是不相信显示的执行时间,也不知道如何测试它们。如果有人能帮助我避免潜在的错误并给我改进的建议,那对我来说意义重大。我对编码还很陌生,所以如果我在任何时候胡言乱语,请原谅。
@echo off
setlocal enabledelayedexpansion
cd TeamCode\src\main\cpp\sources
mkdir ..\exec 2>nul
rem Compile the C++ program
gcc -o ..\exec\jpgtest.exe jpg_usage_example.cpp sdk\jpgengine.cpp Position.cpp -lstdc++
if !ERRORLEVEL! NEQ 0 (
echo Compilation failed. Stopping...
exit /b !ERRORLEVEL!
)
cd ..\exec
rem Record the start time
for /f "tokens=1-3 delims=/:. " %%a in ("!DATE! !TIME!") do (
set "start=%%c-%%b-%%aT%%d:%%e:%%f"
)
rem Run the compiled program
start "" jpgtest.exe
rem Wait for the process to finish
:waitLoop
tasklist | findstr /i "jpgtest.exe" > nul && (
rem Process is still running, wait for 1 millisecond and check again
timeout /t 1 /nobreak > nul
goto :waitLoop
) || (
rem Process has finished, record the end time
for /f "tokens=1-3 delims=/:. " %%a in ("%DATE% %TIME%") do (
set "end=%%c-%%b-%%aT%%d:%%e:%%f"
)
goto :calculateTime
)
:calculateTime
rem Calculate the execution time using PowerShell
powershell -Command "$start = Get-Date; $end = Get-Date; (New-TimeSpan -Start $start -End $end).TotalSeconds" > temp.txt
set /p elapsedTime=<temp.txt
del temp.txt
echo Execution Time: %elapsedTime% seconds
endlocal
我期待更长的执行时间。
Execution Time: 0.0040356 seconds
似乎不适合保存图像。
如果这一切都是使用 PowerShell 完成的,您的生活质量可能会得到改善。这尚未经过测试,但可能确实有效或可以发挥作用。
Set-Location -Path TeamCode\src\main\cpp\sources
New-Item -Path ..\exec -ItemType Directory | Out-Null
# Compile the C++ program
gcc -o ..\exec\jpgtest.exe jpg_usage_example.cpp sdk\jpgengine.cpp Position.cpp -lstdc++
if (0 -ne $LASTEXITCODE) {
Write-Error 'Compilation failed. Stopping...'
exit
}
# Run the compiled program
$RunTime = Measure-Command -Expression { ..\exec\jpgtest.exe }
Write-Host "Execution Time: $($RunTime.ToString())"