我有两个互为副本的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
那些时间之间的关系是稳定的!第一个总是大于第二个,通常要大很多。发生了什么事?
答案 0 :(得分:3)
您也在测量打印时间。您不应该计算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);
如果您不算数,那么您应该问自己why does printf have different times for similar calls ?
。
答案 1 :(得分:2)
实现print
的所有必要功能的“热身”并非微不足道。逐步阅读C运行时库源代码,亲自看看。因此,您第一次拨打printf
的电话通常会比随后的通话慢。
您拨打printf
的电话是在规定的时间内完成的,这在您的实现中是错误的。
从计时中删除printf
调用将解析结果。