相关疑难解决方法(0)

启用优化后,为什么此代码慢6.5倍?

我想基准glibcstrlen功能,出于某种原因,发现它显然执行慢与GCC启用优化,我不知道为什么。

这是我的代码:

#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
    char *s = calloc(1 << 20, 1);
    memset(s, 65, 1000000);
    clock_t start = clock();
    for (int i = 0; i < 128; ++i) {
        s[strlen(s)] = 'A';
    }
    clock_t end = clock();
    printf("%lld\n", (long long)(end - start));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在我的机器上,它输出:

$ gcc test.c && ./a.out
13336
$ gcc -O1 test.c && ./a.out
199004
$ gcc -O2 test.c && ./a.out
83415 …
Run Code Online (Sandbox Code Playgroud)

c performance gcc glibc

64
推荐指数
2
解决办法
3997
查看次数

标签 统计

c ×1

gcc ×1

glibc ×1

performance ×1