我想基准glibc的strlen功能,出于某种原因,发现它显然执行多慢与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)