函数的效率
Created|Updated
|Post Views:
前言
比较两个函数的效率,可以通过它的运行时间来确定。所以可以通过clock()函数来确定某段程序走过多少ticks。
- 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++) { printf("%d ", Lpos->i); Ppos = Ppos->next; } Lpos = Lpos->next; } }
|
clock()
- 从函数的开头,到clock()一直走过多少ticks
- 值的类型为
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); printf("%e\n", duration);
return 0; }
|