我有以下简单程序:
#define N 20
long c[N];
long a[N + N];
void f(void)
{
long *s = c;
long *p = a;
while (p != a + N) *p++ = *s++;
while (p != a + N + N) *p++ = 0;
}
我用以下代码编译它:
/usr/gcc-arm-none-eabi-5_4-2016q3/bin/arm-none-eabi-gcc -mthumb -O3 -o main.o -c main.c
gcc可以方便地分别用memcpy
和memset
替换循环:
00000000 <f>:
0: b570 push {r4, r5, r6, lr}
2: 4d07 ldr r5, [pc, #28] ; (20 <f+0x20>)
4: 4c07 ldr r4, [pc, #28] ; (24 <f+0x24>)
6: 002a movs r2, r5
8: 4907 ldr r1, [pc, #28] ; (28 <f+0x28>)
a: 0020 movs r0, r4
c: f7ff fffe bl 0 <memcpy>
10: 1960 adds r0, r4, r5
12: 002a movs r2, r5
14: 2100 movs r1, #0
16: f7ff fffe bl 0 <memset>
1a: bc70 pop {r4, r5, r6}
1c: bc01 pop {r0}
1e: 4700 bx r0
显然,gcc是聪明的,并且决定库实现更有效,在每种特定情况下可能也可能不是这种情况。我想知道如何避免这种行为,例如,速度不重要,并且不希望库调用。
答案 0 :(得分:4)
好的,搜索https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html会显示以下选项:
-ftree-loop-distribute-patterns
Perform loop distribution of patterns that can be code generated with calls to a library. This flag is enabled by default at -O3.
指定-fno-tree-loop-distribute-patterns
可以避免触及标准库而不会影响其他优化。
答案 1 :(得分:0)
您正在使用标志-O3,它强制编译器运行所有可用的优化方法,尝试使用较低的值,如-O2或-O。