C语言中程序运行时间测试

clock()函数测试程序运行时间

clock()函数:捕捉从程序开始运行到clock()函数被调用所耗费的时间。单位clock tick
常数CLK_TCK: 机器时钟每秒钟所走的时钟打点数

用法举例

#include<stdio.h>
#include<time.h>

clock_t start, stop;    //clock_t是clock()函数返回值的变量类型
double duration;    // 记录被测函数运行时间,以s为单位

int main()
{
    start = clock();    //开始计时
    int n = 1000;
    while(n--)
    {
        MyFunction();   //重复运行被测函数,避免函数调用运行时间过短,便于测定
    }

    stop = clock();
    duration = ((double)(stop - start)) / CLK_TCK;  //计算运行时间
    printf("%lf\n",duration);

    return 0;
}
posted @ 2021-07-21 00:23  echo-hmwnag  阅读(988)  评论(0)    收藏  举报