Issues with Batch Scripts for automated .cpp usage

72 Views Asked by At

I am currently working on a batch file automatically compiles and excecutes a source file and shows the excecution time. I just don't believe the shown excecution times and don't know how to test them. It would mean the world to me if anyone could help me avoid potential bugs and give me tips for improving. I am quite new to coding, so excuse me if I am talking complete nonsense at any point.

@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



I was expecting longer excecution times. Execution Time: 0.0040356 seconds doesn't seem right for saving an image.

1

There are 1 best solutions below

0
lit On BEST ANSWER

This question was tagged with [powershell] and the posted code uses PowerShell. Now it has been removed. There is a possibility that your quality of life could improve if this was all done using PowerShell. This is not tested, but might be something that does or could be made to work.

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"