QB64 中的循环优化



在 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 以包含变量类型

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

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 次函数,结果是:

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

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

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

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

从命令行运行代码(或将 command$ 参数修改到 QB64 菜单中(的循环超过 10 个,如下所示:

# ./test n

其中n是您想要的循环数。

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

相关内容

  • 没有找到相关文章

最新更新