获取程序运行(函数单次运行)所需时间

来源:互联网 发布:c语言open函数 编辑:程序博客网 时间:2024/05/22 16:06

对两个函数进行时间效率上的比较。
clock(); CLK_TCK

#include<stdio.h>#include<time.h>#include<math.h>#define MAXK 1e8//被测函数最大重复调用次数#define MAXN 50clock_t start, stop;double durationOne, durationTwo;void FunOne(int, double[], double);void FunTwo(int, double[], double);int main(){    double a[MAXN];    for (int i = 0;i < MAXN;i++)        a[i] = (double)i;    start = clock();//开始    for (int i = 0;i < MAXK;i++)//重复调用函数以获得充分多的时钟打点数 如果函数运行不到一个时钟打点数 那么输出的消耗时间肯定为0        FunOne(MAXN, a, 1.1);    stop = clock();//结束    durationOne = (double)(stop - start) / CLK_TCK / MAXK;//计算函数单次运行的时间    start = clock();    for (int i = 0;i < MAXK;i++)        FunTwo(MAXN, a, 1.1);    stop = clock();    durationTwo = (double)(stop - start) / CLK_TCK / MAXK;    printf("durationOne=%f durationTwo=%f", durationOne, durationTwo);    //printf("%d", CLK_TCK);//机器每秒钟走的时钟打点数 CLK_TCK=1000;}void FunOne(int n,double a[],double x){    double p = 0;    for (int i = 0;i < n;i++)        p += a[i] * pow(x, i);}void FunTwo(int n, double a[], double x){    double p = a[n];    for (int i = n;i > 0;i--)        p = a[i - 1] + x*p;}
0 0
原创粉丝点击