循环展开

循环展开(Loop unwinding或loop unrolling),是一种牺牲程序的尺寸来加快程序的执行速度的优化方法。可以由程序员完成,也可由编译器自动优化完成。

循环展开最常用来降低循环开销,为具有多个功能单元的处理器提供指令级并行。也有利于指令流水线的调度。

例子

for (i = 1; i <= 60; i++) 
   a[i] = a[i] * b + c;

可以如此循环展开:

for (i = 1; i <= 58; i+=3)
{
  a[i] = a[i] * b + c;
  a[i+1] = a[i+1] * b + c;
  a[i+2] = a[i+2] * b + c;
}

这被称为展开了两次。

优点

  • 分支预测失败减少。
  • 如果循环体内语句没有数据相关,增加了并发执行的机会。
  • 可以在执行时动态循环展开。这种情况在编译时也不可能掌握。

缺点

  • 代码膨胀
  • 代码可读性降低,除非是编译器透明执行循环展开。
  • 循环体内包含递归可能会降低循环展开的得益。[1]

进一步阅读

Kennedy, Ken; Allen, Randy. . Morgan Kaufmann. 2001. ISBN 1-55860-286-0.

参考文献

外部链接

  • Chapter 7, pages 8 to 10, of Michael Abrash's Graphics Programming Black Book is about loop unrolling, with an example in x86 assembly.
  • Generalized Loop Unrolling, gives a concise introduction.
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.