' Stopwatch: TIMER-based, lap times, format output, split display
#COMPILE EXE
#DIM ALL

FUNCTION StartTime AS DOUBLE
    STATIC t AS DOUBLE
    t = TIMER
    FUNCTION = t
END FUNCTION

FUNCTION Elapsed(BYVAL start AS DOUBLE) AS DOUBLE
    FUNCTION = TIMER - start
END FUNCTION

FUNCTION FormatTime(BYVAL seconds AS DOUBLE) AS STRING
    LOCAL h  AS LONG
    LOCAL m  AS LONG
    LOCAL s  AS LONG
    LOCAL ms  AS LONG
    h = INT(seconds / 3600)
    m = INT((seconds - h * 3600) / 60)
    s = INT(seconds - h * 3600 - m * 60)
    ms = INT((seconds - INT(seconds)) * 1000)
    FUNCTION = RIGHT$("00" + FORMAT$(h), 2) + ":" + RIGHT$("00" + FORMAT$(m), 2) + ":" + RIGHT$("00" + FORMAT$(s), 2) + "." + RIGHT$("000" + FORMAT$(ms), 3)
END FUNCTION

FUNCTION SimulateWork(BYVAL iterations AS LONG) AS LONG
    LOCAL i  AS LONG
    LOCAL sum  AS LONG
    sum = 0
    FOR i = 1 TO iterations
        sum = sum + (i MOD 1000)
    NEXT i
    FUNCTION = sum
END FUNCTION

FUNCTION PBMAIN() AS LONG
    LOCAL t0  AS DOUBLE
    LOCAL t1  AS DOUBLE
    LOCAL t2  AS DOUBLE
    LOCAL t3  AS DOUBLE
    LOCAL lap1  AS DOUBLE
    LOCAL lap2  AS DOUBLE
    LOCAL lap3  AS DOUBLE
    PRINT "=== Stopwatch ==="
    PRINT
    t0 = TIMER
    CALL SimulateWork(1000000)
    lap1 = TIMER - t0
    PRINT "Task 1 (1M iterations): " + FormatTime(lap1)
    t1 = TIMER
    CALL SimulateWork(2000000)
    lap2 = TIMER - t1
    PRINT "Task 2 (2M iterations): " + FormatTime(lap2)
    t2 = TIMER
    CALL SimulateWork(500000)
    lap3 = TIMER - t2
    PRINT "Task 3 (500K iterations): " + FormatTime(lap3)
    PRINT "Total: " + FormatTime(lap1 + lap2 + lap3)
    PRINT
    PRINT "Format tests:"
    PRINT "  0s: " + FormatTime(0.0)
    PRINT "  1s: " + FormatTime(1.0)
    PRINT "  61.5s: " + FormatTime(61.5)
    PRINT "  3661.123s: " + FormatTime(3661.123)
    PRINT
    PRINT "Stopwatch tests complete."
    FUNCTION = 0
END FUNCTION
