【问题标题】:How to obtain the execution time of a function in C/C++ [duplicate]如何在C / C ++中获取函数的执行时间[重复]
【发布时间】:2016-04-11 18:34:39
【问题描述】:

我有一个函数可以生成10000个随机数并将它们写入文件。

void generator(char filename[])              
{
    int i;
    int n;
    FILE* fp;
    if((fp=fopen(filename,"w+"))==NULL)
    {
        printf("Fail creating file!");
    }
    srand((unsigned)time(NULL));
    for(i=0;i<10000;i++)
    {
        n=rand()%10000;
        fprintf(fp,"%d ",n);
    }
    fclose(fp);
}

如何使用 C/C++ 获取此函数的执行时间?

【问题讨论】:

标签: c++ c time


【解决方案1】:

代码分析并不是一项特别容易的任务(或者,正如我们在编程中经常说的那样,它是“不平凡的”。问题是因为以秒为单位测量的“执行时间”并不是特别准确或有用。

您想要做的是测量CPU 周期数。这可以使用外部工具来完成,例如callgrind(Valgrind 的工具之一)。 99% 的可能性就是你想要的。

如果您真的想在代码中自己做这件事,那么您将承担一项相当艰巨的任务。我知道第一手资料 - 我用 C++ 编写了一个比较基准测试库,用于实时性能测试。

如果您真的想走这条路,您可以研究 Intel 处理器(主要用于 AMD)或您使用的任何处理器的基准测试。但是,正如我所说,这个话题很大而且很深入,远远超出了 StackOverflow 答案的范围。

【讨论】:

  • 除此之外,当处理器是 Intel 芯片时,它可以在其涡轮增压频率上运行,这使得周期数对于计时也毫无用处,因为它的时钟频率是未知的.这是系统特定的东西,不是可以在机器之间使用的东西。您可以使用基准程序来比较机器的性能,但这就是您所能做的。
  • 虽然你没有解决我的问题,但我更喜欢你的回答。
  • @CarefulNow,我的基准测试库在比较同一台机器上的两个“测试”(当然是为了正确比较而仔细编写)的性能方面做得很好。到目前为止,它适用于所有 Intel/AMD Linux 系统,只要代码是 g++ 编译的。我不打扰该库中的其他编译器或体系结构。它没有给出完美的结果,但它仍然有相当严格和一致的大致估计,与 Callgrind 告诉你的相差不远。
  • @Français,我很高兴它有帮助。如果这是您想要的答案,请单击它旁边的复选标记以“接受”答案。否则,如果您选择其他人的答案,请将他们的答案标记为“已接受”。你应该接受最能引导你朝着你想要的方向前进的答案。
【解决方案2】:

你可以使用chrono库;

#include <chrono>

//*****//

auto start = std::chrono::steady_clock::now();
generator("file.txt")
auto end = std::chrono::steady_clock::now();

std::cout << "genarator() took "
              << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "us.\n";

【讨论】:

    【解决方案3】:

    您已经有一些不错的 C answers 也适用于 C++。
    这里是使用 &lt;chrono&gt; 的原生 C++ 解决方案:

    auto tbegin = std::chrono::high_resolution_clock::now(); 
    ...
    auto tend = std::chrono::high_resolution_clock::now();
    auto tduration = std::chrono::duration_cast<std::chrono::microseconds>(tend - tbegin).count();
    

    优点是您可以非常轻松地从microsecond 切换到millisecondseconds 或任何其他时间测量单位。

    请注意,您可能对时钟精度有操作系统限制(在 Windows 环境中通常为 15 毫秒),因此只有在您确实超过此限制时,这可能会产生有意义的结果。

    【讨论】:

      【解决方案4】:
      void generator(char filename)
      {
          clock_t tStart = clock();
          /* your code here */
          printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
      }
      
      upd. And add #include <ctime>
      

      【讨论】:

        【解决方案5】:

        试试这个

            #include <sys/time.h> 
        
            struct timeval tpstart,tpend; 
        
            double timeuse; 
        
            //get time before generator starts
            gettimeofday(&tpstart,NULL); 
        
            //call generator function
            generator(filename);
        
            //get time after generator ends
            gettimeofday(&tpend,NULL); 
        
            //calculate the used time
            timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec; 
            timeuse/=1000000; 
        
            printf("Used Time:%fsec\n",timeuse);
        

        【讨论】:

        • 有趣,但 [gettimeofday()]man7.org/linux/man-pages/man2/gettimeofday.2.html) 依赖于操作系统(即 POSIX 而不是标准 C/C++)。它还可能受到操作系统时间设置不连续性的影响
        • 我同意你的看法。但我不知道如何避免不连续性。
        【解决方案6】:
        #include <ctime>
         .....
        clock_t start = clock();
        ...//the code you want to get the execution time for
        double elapsed_time = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
        std::cout << elapsed_time << std::endl;//elapsed_time now contains the execution time(in seconds) of the code in between
        

        将在第一次和第二次clock() 调用之间为您提供代码的大致(不准确)执行时间

        【讨论】:

          【解决方案7】:

          暂时把上限设为10000000

          用秒表计时。将时间除以 1000

          【讨论】:

          • 这假设函数的运行时间线性依赖于这个限制,这显然不是打开和关闭文件的情况
          • 这不说明程序被换页或中断。此外,秒表不是很准确(人按开始和停止按钮既不准确也不一致)。
          猜你喜欢
          • 2014-10-04
          • 1970-01-01
          • 2019-08-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-23
          • 2013-03-27
          相关资源
          最近更新 更多