如何测量C函数执行所花费的时间?

要计算函数花费的时间, 我们可以使用clock()可用函数时间。我们可以在测量时间的代码的开头和结尾处调用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()等待输入键终止。

/* 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秒钟, 然后按Enter键, 将获得以下输出。

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

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

来源:

https://www.srcmini02.com/68027.html

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?