gpt4 book ai didi

c - 如果循环的迭代次数在编译时未知,GCC 如何展开循环?

转载 作者:太空狗 更新时间:2023-10-29 16:38:51 24 4
gpt4 key购买 nike

我正在阅读 optimization options for GCC当我找到选项 -funroll-all-loops 时。

它的描述是这样的:

Unroll all loops, even if their number of iterations is uncertain when the loop is entered. This usually makes programs run more slowly. '-funroll-all-loops' implies the same options as '-funroll-loops'

如果循环的迭代次数在编译时未知,编译器如何展开循环?编译器不需要这些信息来展开它吗?它生成什么相应的 C 代码,如果它通常会使程序运行得更慢,这在什么情况下会有用?

最佳答案

这里有一些 C 代码展示了如何做到这一点:

int iterations = 100;
int unrollValue = 8;

while (iterations%unrollvalue)
{
// insert loop code here
iterations--;
}

while (iterations)
{
// insert unrollValue copies of loop code here
iterations-= unrollValue;
}

编译器将用相对跳转替换第一个循环,但这在 C 中不容易表示。请注意,按 2 的幂展开允许编译器使用掩码而不是(昂贵的)除法运算。

关于c - 如果循环的迭代次数在编译时未知,GCC 如何展开循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com