我有两个 C 函数,它们是彼此的副本。在下面的代码中,我打印出它们执行所需的时间。第一个函数(无论是哪个副本)总是比第二个函数花费更长的时间执行。这是为什么?
#include <stdio.h>
#include <time.h> // for clock_t
int binsearch_old (int x, int v[], int n);
int binsearch_new (int x, int v[], int n);
void main ()
{
int x = 4;
int v[10] = { 1,2,3,4,5,6,7,8,9,10 };
int n = 10;
clock_t begin_old = clock();
printf("\nbinsearch_old :: position: %i\n", binsearch_old(x, v, n));
clock_t end_old = clock();
double time_spent_old = (double)(end_old - begin_old) / CLOCKS_PER_SEC;
printf("time spent old: %f\n", time_spent_old);
clock_t begin_new = clock();
printf("\nbinsearch_new :: position: %i\n", binsearch_new(x, v, n));
clock_t end_new = clock();
double time_spent_new = (double)(end_new - begin_new) / CLOCKS_PER_SEC;
printf("time spent new: %f\n", time_spent_new);
}
int binsearch_old (int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if ( x < v[mid])
high = mid - 1;
else if (x > v[mid])
low = mid + 1;
else //found match
return mid;
}
return -1; // no match
}
int binsearch_new (int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (x < v[mid])
high = mid - 1;
else if (x > v[mid])
low = mid + 1;
else //found match
return mid;
}
return -1; // no match
}
在 gcc test.c
和 ./a.out
之后,您会看到如下内容:
binsearch_old :: position: 3
time spent old: 0.000115
binsearch_new :: position: 3
time spent new: 0.000007
而且那段时间关系稳定!第一个总是比第二个大,而且通常大很多。怎么回事?
最佳答案
您也在测量打印时间。你不应该计算 printf
的执行时间。
clock_t begin_old = clock();
int val = binsearch_old(x, v, n);
clock_t end_old = clock();
printf("\nbinsearch_old :: position: %i\n", val);
double time_spent_old = (double)(end_old - begin_old) / CLOCKS_PER_SEC;
printf("time spent old: %f\n", time_spent_old);
如果您不算数那么您应该问问自己为什么 printf 对相似的调用有不同的时间?
。
关于c - 为什么这两个相同的函数有截然不同的执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56566922/