当处理密集循环时,可以加速循环展开和减少循环条件判断的开销,如下:
- 例子使用IDE写的,举个例子而已。
- 条件判断是有开销的,条件判断次数越多,开销越大。
- 该写法最开始由Tom Duff在1983年发明的,最初是用于优化图形处理
#include <QCoreApplication>
#include <QDebug>
static int do_something();
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int count = 97;
//循环展开,减少循环条件的判断次数来减少循环中的指令数量,也减少判断时间;
int result_t_i = 0;
int realWhileTimes_t_i = (count + 7 ) >> 3;
//当case为连续时,编译器会使用表结构优化,例如:gcc -O3
switch (count & 0x0111u) {
case 0: do { result_t_i += do_something(); [[gnu::fallthrough]];
case 7: result_t_i += do_something(); [[gnu::fallthrough]]; //c14c11
case 6: result_t_i += do_something(); [[fallthrough]]; //c17
case 5: result_t_i += do_something(); [[fallthrough]];
case 4: result_t_i += do_something(); [[fallthrough]];
case 3: result_t_i += do_something(); [[fallthrough]];
case 2: result_t_i += do_something(); [[fallthrough]];
case 1: result_t_i += do_something(); } while(--realWhileTimes_t_i > 0);
}
qDebug() << "whileTimes_T:" << realWhileTimes_t_i << " result_t_i:" << result_t_i;
return a.exec();
}
static int __attribute__((pure)) __attribute__((always_inline)) do_something(void) {
return 1;
}