duan0403788996 2016-12-26 07:39
浏览 50
已采纳

Go运行时是否在每次迭代时都评估for循环条件?

Here is a code snippet from the book "The Go Programming Language":

for t := 0.0; t < cycles*2*math.Pi; t += res {
    ...
}

It appears that the expression in the for loop condition t < cycles*2*math.Pi must be evaluated before every iteration of the for loop. Or, does the compiler optimize this by pre-calculating the result of the expression (assuming none of the variables change during the iteration)? Does the above style of coding affect performance?

  • 写回答

3条回答 默认 最新

  • duanfa0072 2016-12-26 08:27
    关注

    This really depends on the Go version but go version go1.7 windows/amd64 does appear to calculate the value once.

    Go code:

    var cycles = 10.0
    var res = 1000.0
    for t := 0.0; t < cycles*2*math.Pi; t += res {
    }
    

    Asm code:

    movsd   [rsp+58h+var_20], xmm0
    mov     [rsp+58h+var_18], 0
    mov     [rsp+58h+var_10], 0
    lea     rax, qword_494500
    mov     [rsp+58h+var_58], rax
    lea     rax, [rsp+58h+var_20]
    mov     [rsp+58h+var_50], rax
    mov     [rsp+58h+var_48], 0
    call    runtime_convT2E
    mov     rax, [rsp+58h+var_40]
    mov     rcx, [rsp+58h+a] ; a
    mov     [rsp+58h+var_18], rax
    mov     [rsp+58h+var_10], rcx
    lea     rax, [rsp+58h+var_18]
    mov     [rsp+58h+var_58], rax
    mov     [rsp+58h+var_50], 1
    mov     [rsp+58h+var_48], 1
    call    fmt_Println
    movsd   xmm0, cs:$f64_408f400000000000
    movsd   xmm1, [rsp+58h+t]
    addsd   xmm0, xmm1
    movsd   [rsp+58h+t], xmm0
    movsd   xmm1, cs:$f64_404f6a7a2955385e
    ucomisd xmm1, xmm0
    ja      loc_401083
    

    f64_404f6a7a2955385e is a precalculated double value equal to 10 * 2 * math.Pi or 62.8318530718

    Go compiler recently switched to SSA, so these kind of optimizations will just keep improving as they greatly benefit from it. For now SSA is only available on amd64:

    Compiler Toolchain

    This release includes a new code generation back end for 64-bit x86 systems, following a proposal from 2015 that has been under development since then. The new back end, based on SSA, generates more compact, more efficient code and provides a better platform for optimizations such as bounds check elimination.

    1.8 should have it for all supported architectures:

    Compiler Toolchain

    Go 1.7 introduced a new compiler back end for 64-bit x86 systems. In Go 1.8, that back end has been developed further and is now used for all architectures.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题