如何在C语言中测量函数所用的时间?

为了计算一个过程所花费的时间,我们可以使用 时钟() 可用的功能 时间H .我们可以在测量时间的代码的开头和结尾调用时钟函数,减去值,然后除以 每秒时钟 (每秒时钟滴答数)以获取处理器时间,如下所示。

null
     #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()等待回车键终止。

/* 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 " );
printf ( "Press enter to stop fun " );
while (1)
{
if ( getchar ())
break ;
}
printf ( "fun() ends " );
}
// 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 " , time_taken);
return 0;
}


输出:等待约4秒钟后,点击回车键,即可获得以下输出。

fun() starts
Press enter to stop fun

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

如何在Linux Shell上查找命令/程序占用的时间?

参考资料: http://www.gnu.org/software/libc/manual/html_node/CPU-Time.html http://www.cplusplus.com/reference/ctime/clock/?kw=clock

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享