前言

比较两个函数的效率,可以通过它的运行时间来确定。所以可以通过clock()函数来确定某段程序走过多少ticks。

  • 如何确定运行时间
  1. O(N) N是for循环的运行次数。如果是while循环的话,则要看结束条件和内部,要循环多少次
运行时间为O(L+P)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void PrintLots(List L, List P)
{
int Counter = 1;
Position Ppos = L, Lpos = P;

while (Ppos->next != NULL && Lpos->next != NULL)
{
if(Ppos->i == Counter++)//每次循环不一定执行,运行时间为O(P)
{
printf("%d ", Lpos->i);
Ppos = Ppos->next;
}
Lpos = Lpos->next;//每次都循环都执行,运行时间为O(L)
}
}

clock()

  • 需要time.h头文件

  • 无参数

  • 返回值

  1. 从函数的开头,到clock()一直走过多少ticks
  2. 值的类型为clock_t
  • 注意的问题
    可能有的函数运行的时间都不到一个ticks,所以要通过循环去将此函数执行多次

示例

查看printN()的效率
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<stdio.h>
#include<time.h>
void printN(int n)
{
if(n)
{
printN(n - 1);
printf("%d\n", n);
}

}
int main()
{
clock_t start, stop;
double duration;
int n;
scanf("%d", &n);

start = clock();
printN(n);
stop = clock();

duration = (double)(stop - start);//强制转换为double
printf("%e\n", duration);

return 0;
}