c - 为什么这两个相同的函数有截然不同的执行时间?

标签 c

我有两个 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/

相关文章:

c - 我想知道 OCIStmt 结构

c - 我想我以错误的方式声明和使用了数组

c - 在C中使用线程实现管道

c - printf 未对齐输出

C 无法编译 : Can't find math. h 函数

c - 同一变量的两个枚举定义

c - clang 试图优化这个简单的递归算法是什么?

c - 从图像中提取较小的图像

c - 为什么我无法扫描%c字符?

c - 如何测量 (linux C) 函数的执行时间?