语句执行时间的计时 - C++

8

1
在语句开始执行之前记录时间,然后让它们执行,再次获取时间并从第一次记录的时间中减去。 - Ionut Hulub
8个回答

24

你可以使用标准库中的 <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;
    }
}

5

你需要自己测量时间。我通常使用的小秒表类如下:

#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。


4

对于这个问题,可以使用std::chrono或者boost::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);

1
它是 high_resolution_clock,而不是 high_resolution_timer - Benoit Blanchon
1
@BenoitBlanchon 谢谢您,对于我的错误我很抱歉,我已编辑了我的答案。 - BigBoss

2

您需要编写一个简单的计时系统。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;
}

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

2
可能是重复的问题:如何在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年以来就存在了。根据维基百科:https://en.wikipedia.org/wiki/SpeedStep 我必须投反对票。 - Joeppie

1
如果您正在使用GNU gcc/g++:
尝试重新编译并加上--coverage参数,然后重新运行程序,并使用gprof工具分析生成的文件。它还会打印函数的执行时间。
编辑:请使用-pg进行编译和链接,而不是--coverage,--coverage是用于gcov(实际执行哪些行)。

我对 -pg 的经验是它会破坏许多带有 errno 设置为 EINTR 的调用。是的,修复一个或两个这样的调用很容易。但如果你有 100,000 行代码,那就祝你好运了... - Alexis Wilke

0
这是一段非常好的代码片段,适用于Windows和Linux操作系统:https://dev59.com/FnI-5IYBdhLWcg3wbHu-#1861337
要使用它,运行代码并将结果保存为“开始时间”,然后在操作完成后保存为“结束时间”。根据需要进行减法和除法运算,以达到所需的精度。

2
一个简单的链接到另一个答案本身并不是一个答案。请使用“标记”功能来标记重复的问题。 - Mat
@Mat:我不确定mrowa是否有足够的声望来进行标记... - Matthieu M.
@Mat:我喜欢注明出处,这就是为什么我会链接到代码片段而不是复制粘贴的原因 - 不过,你说对了,可能存在重复的情况。(是的,在15个声望以上时现在启用了标记功能。) - mrówa

-1
你可以使用#include <ctime>头文件。它的函数及其用途在这里。假设你想要观察代码花费了多少时间。你必须在该部分开始之前取得当前时间,然后在该部分结束之后再取得另一个当前时间。然后取这两个时间的差值。预先定义好的函数在ctime中声明,可以完成所有这些工作。只需查看上面的链接即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接