循环展开 简单的循环可以展开以获取更好的性能,但需要付出代码体积增加的代价。循环展开后,循环计数应该越来越小从而执行更少的代码分支。如果循环迭代次数只有几次,那么可以完全展开循环,以便消除循坏带来的负担。 这会带来很大的不同。循环展开可以带非常可观的节省性能,原因是代码不用每次循环需要检查和增加i的值。例如:
======003 编译器通常会像上面那样展开简单的,迭代次数固定的循环。但是像下面的代码: - for(i=0;i< limit;i++) { ... }
下面的代码(Example 1)明显比使用循环的方式写的更长,但却更有效率。block-sie的值设置为8仅仅适用于测试的目的,只要我们重复执行“loop-contents”相同的次数,都会有很好的效果。 在这个例子中,循环条件每8次迭代才会被检查,而不是每次都进行检查。由于不知道迭代的次数,一般不会被展开。因此,尽可能的展开循环可以让我们获得更好的执行速度。 - //Example 1
-
- #include<STDIO.H>
-
- #define BLOCKSIZE (8)
-
- void main(void)
- {
- int i = 0;
- int limit = 33; /* could be anything */
- int blocklimit;
-
- /* The limit may not be divisible by BLOCKSIZE,
- * go as near as we can first, then tidy up.
- */
- blocklimit = (limit / BLOCKSIZE) * BLOCKSIZE;
-
- /* unroll the loop in blocks of 8 */
- while( i < blocklimit )
- {
- printf("process(%d)\n", i);
- printf("process(%d)\n", i+1);
- printf("process(%d)\n", i+2);
- printf("process(%d)\n", i+3);
- printf("process(%d)\n", i+4);
- printf("process(%d)\n", i+5);
- printf("process(%d)\n", i+6);
- printf("process(%d)\n", i+7);
-
- /* update the counter */
- i += 8;
-
- }
-
- /*
- * There may be some left to do.
- * This could be done as a simple for() loop,
- * but a switch is faster (and more interesting)
- */
-
- if( i < limit )
- {
- /* Jump into the case at the place that will allow
- * us to finish off the appropriate number of items.
- */
-
- switch( limit - i )
- {
- case 7 : printf("process(%d)\n", i); i++;
- case 6 : printf("process(%d)\n", i); i++;
- case 5 : printf("process(%d)\n", i); i++;
- case 4 : printf("process(%d)\n", i); i++;
- case 3 : printf("process(%d)\n", i); i++;
- case 2 : printf("process(%d)\n", i); i++;
- case 1 : printf("process(%d)\n", i);
- }
- }
-
- }
|