Easily measure elapsed time

前端 未结 26 2202
栀梦
栀梦 2020-11-22 04:13

I am trying to use time() to measure various points of my program.

What I don\'t understand is why the values in the before and after are the same? I understand thi

26条回答
  •  青春惊慌失措
    2020-11-22 04:57

    You can abstract the time measuring mechanism and have each callable's run time measured with minimal extra code, just by being called through a timer structure. Plus, at compile time you can parametrize the timing type (milliseconds, nanoseconds etc).

    Thanks to the review by Loki Astari and the suggestion to use variadic templates. This is why the forwarded function call.

    #include 
    #include 
    
    template
    struct measure
    {
        template
        static typename TimeT::rep execution(F&& func, Args&&... args)
        {
            auto start = std::chrono::steady_clock::now();
            std::forward(func)(std::forward(args)...);
            auto duration = std::chrono::duration_cast< TimeT> 
                                (std::chrono::steady_clock::now() - start);
            return duration.count();
        }
    };
    
    int main() {
        std::cout << measure<>::execution(functor(dummy)) << std::endl;
    }
    

    Demo

    According to the comment by Howard Hinnant it's best not to escape out of the chrono system until we have to. So the above class could give the user the choice to call count manually by providing an extra static method (shown in C++14)

    template
    static auto duration(F&& func, Args&&... args)
    {
        auto start = std::chrono::steady_clock::now();
        std::forward(func)(std::forward(args)...);
        return std::chrono::duration_cast(std::chrono::steady_clock::now()-start);
    } 
    
    // call .count() manually later when needed (eg IO)
    auto avg = (measure<>::duration(func) + measure<>::duration(func)) / 2.0;
    

    and be most useful for clients that

    "want to post-process a bunch of durations prior to I/O (e.g. average)"


    The complete code can be found here. My attempt to build a benchmarking tool based on chrono is recorded here.


    If C++17's std::invoke is available, the invocation of the callable in execution could be done like this :

    invoke(forward(func), forward(args)...);
    

    to provide for callables that are pointers to member functions.

提交回复
热议问题