1

在 QB64 中有一个关于循环优化的循环:

DIM N AS DOUBLE, X(100000000) AS DOUBLE
T! = TIMER
FOR N = 1 to 100000000
    IF X(N) THEN
        PRINT X(N)
        EXIT FOR
    END IF
NEXT
PRINT TIMER - T!

是否比以下更快:

DIM N AS DOUBLE, X(100000000) AS DOUBLE
T! = TIMER
FOR N = 1 to 100000000
    IF X(N) <> 0  THEN
        PRINT X(N)
        EXIT FOR
    END IF
NEXT
PRINT TIMER - T!

编辑:09-18-2018 包括变量类型

4

1 回答 1

1

我写了这段代码来评估你的测试:

REM Delete REM to enable console runs
REM $CONSOLE:ONLY
REM _DEST _CONSOLE

DIM SHARED N AS DOUBLE, X(100000000) AS DOUBLE

S# = 0: ZC% = 0
T% = 10
IF COMMAND$ <> "" THEN
    T% = VAL(COMMAND$)
END IF

IF T% > 999 THEN T% = 999

FOR I% = 1 TO T%
    A# = TRYA
    B# = TRYB

    D# = A# - B#
    PRINT USING "Case A ... : #.########"; A#
    PRINT USING "Case B ... : #.########"; B#
    PRINT USING "Diff ..... : #.########"; D#;

    A$ = ""
    IF ABS(D#) < 0.00000001 THEN
        ZC% = ZC% + 1
        A$ = "*"
    END IF

    S# = S# + A# - B#

    PRINT A$
    PRINT

    REM INKEY$ doesn't work in console mode!
    A$ = INKEY$
    IF A$ = CHR$(27) THEN
        I% = I% + 1: EXIT FOR
    END IF
NEXT

PRINT USING "Avrg A - B : #.########"; S# / (I% - 1)
PRINT USING "0 diff:### on ### tryes"; ZC%, (I% - 1)
PRINT

PRINT "Hit a key to exit!"
REM INPUT$ doesn't work in console mode!
A$ = INPUT$(1)
SYSTEM


FUNCTION TRYA#
    T# = TIMER
    FOR N = 1 TO 100000000
        IF X(N) THEN
            PRINT X(N)
            EXIT FOR
        END IF
    NEXT
    A# = TIMER - T#

    TRYA = A#
END FUNCTION

FUNCTION TRYB#
    T# = TIMER
    FOR N = 1 TO 100000000
        IF X(N) <> 0 THEN
            PRINT X(N)
            EXIT FOR
        END IF
    NEXT
    A# = TIMER - T#

    TRYB = A#
END FUNCTION

这两个不同的例程被插入到两个函数中:TRYATRYB

我用一个运行 999 次函数的循环启动了这个 SW,结果是:

Avrg. A - B: 0.00204501
0 diff:359 on 999 tryes

然后我启动了 10 次循环,结果是:

Avrg. A - B: -.01640625
0 diff:  1 on  10 tryes

然后我启动了 15 次循环,结果是:

Avrg. A - B: 0.00026042
0 diff:  5 on  15 tryes

因为我们在多线程环境中启动 SW 我不认为这是一个很好的测试,但有一些结果:

  1. 在两种情况下,无差异(0 diff)的结果是所有循环的三分之一。
  2. 在两种情况下,该功能似乎TRYA较慢。
  3. 在一种情况下,该功能似乎TRYB较慢。

看这些结果,我想,我们可以认为这两个函数是等价的!

您从命令行运行代码(或将 command$ 参数修改到 QB64 菜单中)获得了 10 多个循环,如下所示:

# ./test n

n您想要的循环数在哪里。

SW 是使用带有 -O3 优化选项的 gcc 编译的。(为此,您必须修改文件[/opt/]qb64/internal/c/makeline_lnx.txt

于 2019-01-03T13:20:23.900 回答