我有两个相互复制的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: %in", 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: %fn", time_spent_old);
clock_t begin_new = clock();
printf("nbinsearch_new :: position: %in", 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: %fn", 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: %in", val);
double time_spent_old = (double)(end_old - begin_old) / CLOCKS_PER_SEC;
printf("time spent old: %fn", time_spent_old);
如果你不算,那么你应该问自己why does printf have different times for similar calls ?
.
实现print
所需的所有功能的"预热"并非不可忽视。逐步浏览 C 运行时库源代码,亲自查看。因此,您向printf
发出的第一次调用通常比后续调用慢。
对printf
的调用在计时范围内,这是实现中的错误。
从计时中删除printf
调用将等于结果。