运行时间测量技术

发布时间:2019-06-22 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了运行时间测量技术脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

在优化某段程序之前,我们往往需要确定其运行时间,通过对比优化前后的时间,来衡量优化的力度。

那么问题来了,除了借助操作系统 time 命令这种方式,有没有直接在代码中嵌入时间测量的方法呢?

C++ 中比较传统的方式是使用 C 库中的<ctime>.

#include <ctime>
using namespace std;

int main()
{
    clock_t begin = clock();

    // your codes

    clock_t end = clock();
    double elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
    cout << elapsed_secs << " s" << endl;
}

这种方式实际上是可以精确到毫秒的,如果再想更加精确,就有点难了。


今天介绍一种借助 std::chrono::duration 与 lambda 函数的方法,相比之下更加 C++ 一些。

#include <chrono>

template<typename TimeT = std::chrono::milliseconds>
struct measure
{
    template<typename F, typename ...Args>
    static typename TimeT::rep execution(F func, Args&&... args)
    {
        auto start = std::chrono::system_clock::now();

        // Now call the function with all the parameters you need.
        func(std::forward<Args>(args)...);

        auto duration = std::chrono::duration_cast< TimeT>
            (std::chrono::system_clock::now() - start);

        return duration.count();
    }
};

struct functor
{
    int state;
    functor(int state) : state(state) {}
    void operator()() const
    {
        std::cout << "In functor run for ";
    }
};

void func()
{
    std::cout << "In function, run for " << std::endl;
}

int main() 
{
    // codes directly
    std::cout << measure<>::execution([&]() {
        // your code
    }) << " ms" << std::endl;

    // functor
    std::cout << measure<>::execution(functor(3)) << std::endl;

    // function
    std::cout << measure<>::execution(func);
}

改变精度,仅需修改 template<typename TimeT = std::chrono::milliseconds> 中的参数即可:

  • milliseconds : 毫秒
  • microseconds : 微秒
  • nanoseconds : 纳秒

脚本宝典总结

以上是脚本宝典为你收集整理的运行时间测量技术全部内容,希望文章能够帮你解决运行时间测量技术所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。