📜  如何测量C中的函数所花费的时间?

📅  最后修改于: 2021-05-30 05:35:42             🧑  作者: Mango

要计算一个进程花费的时间,我们可以使用clock()函数,它是可用的time.h。我们可以在要测量时间的代码的开头和结尾处调用Clock函数,将其相减,然后除以CLOCKS_PER_SEC(每秒的时钟滴答数)以获取处理器时间,如下所示。

#include 
     
     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 
#include 
  
// 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

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”