【问题标题】:Timing the execution of statements - C++ [duplicate]定时执行语句 - C++ [重复]
【发布时间】:2012-10-14 15:13:42
【问题描述】:

可能重复:
How to Calculate Execution Time of a Code Snippet in C++

如何获取某些 C++ 代码中一组特定语句所花费的时间?

类似于 Linux 下的 time 实用程序,但仅适用于某些特定语句。

【问题讨论】:

  • 保存语句开始执行之前的时间,然后让它们执行,再次获取时间并从中减去第一次。

标签: c++ benchmarking


【解决方案1】:

您可以使用标准库中的<chrono> 标头:

#include <chrono>
#include <iostream>

unsigned long long fib(unsigned long long n) {
    return (0==n || 1==n) ? 1 : fib(n-1) + fib(n-2);
}

int main() {
    unsigned long long n = 0;
    while (true) {
        auto start = std::chrono::high_resolution_clock::now();
        fib(++n);
        auto finish = std::chrono::high_resolution_clock::now();

        auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);
        std::cout << microseconds.count() << "µs\n";
        if (microseconds > std::chrono::seconds(1))
            break;
    }
}

【讨论】:

    【解决方案2】:

    您需要自己测量时间。我通常使用的小秒表类是这样的:

    #include <chrono>
    #include <iostream>
    
    template <typename Clock = std::chrono::steady_clock>
    class stopwatch
    {
        typename Clock::time_point last_;
    
    public:
        stopwatch()
            : last_(Clock::now())
        {}
    
        void reset()
        {
            *this = stopwatch();
        }
    
        typename Clock::duration elapsed() const
        {
            return Clock::now() - last_;
        }
    
        typename Clock::duration tick()
        {
            auto now = Clock::now();
            auto elapsed = now - last_;
            last_ = now;
            return elapsed;
        }
    };
    
    template <typename T, typename Rep, typename Period>
    T duration_cast(const std::chrono::duration<Rep, Period>& duration)
    {
        return duration.count() * static_cast<T>(Period::num) / static_cast<T>(Period::den);
    }
    
    int main()
    {
        stopwatch<> sw;
        // ...
        std::cout << "Elapsed: " << duration_cast<double>(sw.elapsed()) << '\n';
    }
    

    duration_cast 可能不是函数的最佳名称,因为标准库中已经存在具有此名称的函数。随意想出一个更好的。 ;)

    编辑:请注意,chrono 来自 C++11。

    【讨论】:

      【解决方案3】:

      std::chronoboost::chrono(如果您的编译器不支持 C++11)可以用于此。

      std::chrono::high_resolution_clock::time_point start( 
          std::chrono::high_resolution_clock::now() );
      ....
      std::cout << (std::chrono::high_resolution_clock::now() - start);
      

      【讨论】:

      • 这是high_resolution_clock,而不是high_resolution_timer
      • @BenoitBlanchon 谢谢你,对不起,我编辑了我的答案
      【解决方案4】:

      你需要编写一个简单的计时系统。 c++中没有内置方式。

      #include <sys/time.h>
      
      class Timer
      {
      private:
          struct timeval start_t;
      public:
          double start() { gettimeofday(&start_t, NULL); }
          double get_ms() {
             struct timeval now;
             gettimeofday(&now, NULL);
             return (now.tv_usec-start_t.tv_usec)/(double)1000.0 +
                    (now.tv_sec-start_t.tv_sec)*(double)1000.0;
          }
          double get_ms_reset() {
            double res = get_ms();
            reset();
            return res;
          }
          Timer() { start(); }
      };
      
      int main()
      {
        Timer t();
        double used_ms;
      
        // run slow code..
        used_ms = t.get_ms_reset();
      
        // run slow code..
        used_ms += t.get_ms_reset();
        return 0;
      }
      

      请注意,测量本身会显着影响运行时间。

      【讨论】:

        【解决方案5】:

        可能重复:How to Calculate Execution Time of a Code Snippet in C++

        您可以使用 time.h C 标准库(在http://www.cplusplus.com/reference/clibrary/ctime/ 有更详细的解释)。以下程序可以满足您的要求:

        #include <iostream>
        #include <time.h>
        
        using namespace std;
        
        int main()
        {
            clock_t t1,t2;
            t1=clock();
            //code goes here
            t2=clock();
            float diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC;
            cout << "Running time: " << diff << endl;
        
            return 0;
        }
        

        您也可以这样做:

        int start_s=clock();
        // the code you wish to time goes here
        int stop_s=clock();
        cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl;
        

        【讨论】:

        • 这不好。如果您计算每秒时钟数,那么当时钟速度发生变化时,您将获得差异。该技术自 2005 年以来就已经存在。根据维基百科:en.wikipedia.org/wiki/SpeedStep 我不得不对此投反对票。
        【解决方案6】:

        如果您使用的是 GNU gcc/g++:

        尝试使用 --coverage 重新编译,重新运行程序并使用 gprof 实用程序分析生成的文件。它还会打印函数的执行时间。

        编辑:编译和链接使用-pg,而不是--coverage,--coverage 用于gcov(实际执行哪些行)。

        【讨论】:

        • 只有我对-pg 的经验是,它会中断许多呼叫,并将errno 设置为EINTR。是的,修复一个甚至两个这样的呼叫很容易。如果你有 100,000 行代码,祝你好运……
        【解决方案7】:

        这是非常好的 sn-p 代码,在 windows 和 linux 上运行良好:https://stackoverflow.com/a/1861337/1483826
        要使用它,运行它并将结果保存为“开始时间”和操作之后 - “结束时间”。减去和除以您需要的任何精度。

        【讨论】:

        • 指向另一个答案的普通链接本身并不是一个答案。请使用“标记”功能来表示重复的问题。
        • @Mat:我不确定 mrowa 是否有足够的声望来标记...
        • @Mat:我喜欢相信起源,这就是为什么我链接到 sn-ps 而不是复制和粘贴 - 不过,你对可能的重复是完全正确的。 (是的,现在从 15 代表启用标记)
        【解决方案8】:

        您可以使用#inclide &lt;ctime&gt; 标头。 It's functions and their uses are here。假设您想查看代码花费了多少时间。您必须在该部分开始之前获取当前时间,并在该部分结束后获取另一个当前时间。然后取这两次的差。在ctime 中声明了现成的函数来完成所有这些工作。只需查看上面的链接。

        【讨论】:

          猜你喜欢
          • 2015-08-26
          • 2012-09-02
          • 1970-01-01
          • 1970-01-01
          • 2021-06-17
          • 2017-11-08
          • 2019-11-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多