吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C语言如何测量函数所花费的时间

C语言如何测量函数所花费的时间

来源:网络 | 更新时间:2022-01-30 09:02:16
要计算一个进程所花费的时间,我们可以使用time.h中的clock()函数。我们可以在我们测量时间的代码的开头和结尾调用时钟函数,减去这些值,然后除以CLOCKS_PER_SEC(每秒时钟滴答数)以获得处理器时间,如下所示。
 #include <time.h>

clock_t start, end;
double cpu_time_used;

start = clock();
... /* Do the work. */
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
以下是一个示例 C 程序,我们在其中测量 fun() 所花费的时间。函数 fun() 等待 Enter 键按下终止。

/* Program to demonstrate time taken by function fun() */
#include <stdio.h>
#include <time.h>

// A function that terminates when enter key is pressed
void fun()
{
printf("fun() starts n");
printf("Press enter to stop fun n");
while(1)
{
if (getchar())
break;
}
printf("fun() ends n");
}

// The main program calls fun() and measures time taken by fun()
int main()
{
// Calculate the time taken by fun()
clock_t t;
t = clock();
fun();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds

printf("fun() took %f seconds to execute n", time_taken);
return 0;
}
输出:等待约4秒后按回车键得到如下输出。
fun() starts
Press enter to stop fun

fun() ends
fun() took 4.017000 seconds to execute

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com