很多人写道,这个版本get_len
更快:
int get_len(char* str)
{
char *cpy;
cpy = str;
while (*cpy)
{
++cpy;
}
return (cpy - str);
}
比这个:
int get_len2(char* str)
{
int i;
i = 0;
while (str[i])
{
i++;
}
return i;
}
但是当我检查运行时间时,第二个似乎更快......
所以我的问题是为什么?
这是主要功能测试:
int main()
{
clock_t begin, end;
double time_spent;
begin = clock();
printf("%d\n", get_len("HEEEEY"));
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%f\n", time_spent);
begin = clock();
printf("%d\n", get_len2("HEEEEY"));
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%f", time_spent);
return 0;
}
输出 :
6
0.000025
6
0.000001%