Measuring execution time of a function in C++

后端 未结 11 809
小鲜肉
小鲜肉 2020-11-22 12:59

I want to find out how much time a certain function takes in my C++ program to execute on Linux. Afterwards, I want to make a speed comparison . I saw sever

11条回答
  •  余生分开走
    2020-11-22 13:24

    Here is an excellent header only class template to measure the elapsed time of a function or any code block:

    #ifndef EXECUTION_TIMER_H
    #define EXECUTION_TIMER_H
    
    template
    class ExecutionTimer {
    public:
        using Clock = std::conditional_t;
    private:
        const Clock::time_point mStart = Clock::now();
    
    public:
        ExecutionTimer() = default;
        ~ExecutionTimer() {
            const auto end = Clock::now();
            std::ostringstream strStream;
            strStream << "Destructor Elapsed: "
                      << std::chrono::duration_cast( end - mStart ).count()
                      << std::endl;
            std::cout << strStream.str() << std::endl;
        }    
    
        inline void stop() {
            const auto end = Clock::now();
            std::ostringstream strStream;
            strStream << "Stop Elapsed: "
                      << std::chrono::duration_cast(end - mStart).count()
                      << std::endl;
            std::cout << strStream.str() << std::endl;
        }
    
    }; // ExecutionTimer
    
    #endif // EXECUTION_TIMER_H
    

    Here are some uses of it:

    int main() {
        { // empty scope to display ExecutionTimer's destructor's message
             // displayed in milliseconds
             ExecutionTimer timer;
    
             // function or code block here
    
             timer.stop();
    
        } 
    
        { // same as above
            ExecutionTimer timer;
    
            // code block here...
    
            timer.stop();
        }
    
        {  // same as above
           ExecutionTimer timer;
    
           // code block here...
    
           timer.stop();
    
        }
    
        {  // same as above
           ExecutionTimer timer;
    
           // code block here...
    
           timer.stop();
    
        }              
    
        return 0;
    }
    

    Since the class is a template we can specify real easily in how we want our time to be measured & displayed. This is a very handy utility class template for doing bench marking and is very easy to use.

提交回复
热议问题