Timer function to provide time in nano seconds using C++

前端 未结 16 2339
野趣味
野趣味 2020-11-22 06:02

I wish to calculate the time it took for an API to return a value. The time taken for such an action is in the space of nano seconds. As the API is a C++ class/function, I a

16条回答
  •  清歌不尽
    2020-11-22 06:29

    Here is a nice Boost timer that works well:

    //Stopwatch.hpp
    
    #ifndef STOPWATCH_HPP
    #define STOPWATCH_HPP
    
    //Boost
    #include 
    //Std
    #include 
    
    class Stopwatch
    {
    public:
        Stopwatch();
        virtual         ~Stopwatch();
        void            Restart();
        std::uint64_t   Get_elapsed_ns();
        std::uint64_t   Get_elapsed_us();
        std::uint64_t   Get_elapsed_ms();
        std::uint64_t   Get_elapsed_s();
    private:
        boost::chrono::high_resolution_clock::time_point _start_time;
    };
    
    #endif // STOPWATCH_HPP
    
    
    //Stopwatch.cpp
    
    #include "Stopwatch.hpp"
    
    Stopwatch::Stopwatch():
        _start_time(boost::chrono::high_resolution_clock::now()) {}
    
    Stopwatch::~Stopwatch() {}
    
    void Stopwatch::Restart()
    {
        _start_time = boost::chrono::high_resolution_clock::now();
    }
    
    std::uint64_t Stopwatch::Get_elapsed_ns()
    {
        boost::chrono::nanoseconds nano_s = boost::chrono::duration_cast(boost::chrono::high_resolution_clock::now() - _start_time);
        return static_cast(nano_s.count());
    }
    
    std::uint64_t Stopwatch::Get_elapsed_us()
    {
        boost::chrono::microseconds micro_s = boost::chrono::duration_cast(boost::chrono::high_resolution_clock::now() - _start_time);
        return static_cast(micro_s.count());
    }
    
    std::uint64_t Stopwatch::Get_elapsed_ms()
    {
        boost::chrono::milliseconds milli_s = boost::chrono::duration_cast(boost::chrono::high_resolution_clock::now() - _start_time);
        return static_cast(milli_s.count());
    }
    
    std::uint64_t Stopwatch::Get_elapsed_s()
    {
        boost::chrono::seconds sec = boost::chrono::duration_cast(boost::chrono::high_resolution_clock::now() - _start_time);
        return static_cast(sec.count());
    }
    

提交回复
热议问题