要计算一个进程所花费的时间,我们可以使用time.h中的clock()函数。我们可以在我们测量时间的代码的开头和结尾调用时钟函数,减去这些值,然后除以CLOCKS_PER_SEC(每秒时钟滴答数)以获得处理器时间,如下所示。
以下是一个示例 C 程序,我们在其中测量 fun() 所花费的时间。函数 fun() 等待 Enter 键按下终止。
输出:等待约4秒后按回车键得到如下输出。
#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;
/* 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;
}
fun() starts Press enter to stop fun fun() ends fun() took 4.017000 seconds to execute