定时执行语句 - C++

use*_*079 5 c++ benchmarking

可能重复:
如何计算C++中代码片段的执行时间

我如何在一些C++代码中获得特定语句集所花费的时间?

timeLinux下的实用程序,但只适用于某些特定的语句.

bam*_*s53 15

您可以使用<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;
    }
}
Run Code Online (Sandbox Code Playgroud)


coo*_*451 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';
}
Run Code Online (Sandbox Code Playgroud)

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

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


Joh*_*oma 1

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

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

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