Computing CPU time in C++ on Windows

后端 未结 5 903
無奈伤痛
無奈伤痛 2021-02-03 14:50

Is there any way in C++ to calculate how long does it take to run a given program or routine in CPU time?

I work with Visual Studio 2008 running on Wind

5条回答
  •  星月不相逢
    2021-02-03 15:08

    The clock() function [as provided by Visual C++ 2008] doesn't return processor time used by the program, while it should (according to the C standard and/or C++ standard). That said, to measure CPU time on Windows, I have this helper class (which is inevitably non-portable):

    class ProcessorTimer
    {
      public:
        ProcessorTimer() { start(); }
        void start() { ::GetProcessTimes(::GetCurrentProcess(), &ft_[3], &ft_[2], &ft_[1], &ft_[0]); }
        std::tuple stop()
        {
            ::GetProcessTimes(::GetCurrentProcess(), &ft_[5], &ft_[4], &ft_[3], &ft_[2]);
            ULARGE_INTEGER u[4];
            for (size_t i = 0; i < 4; ++i)
            {
                u[i].LowPart = ft_[i].dwLowDateTime;
                u[i].HighPart = ft_[i].dwHighDateTime;
            }
            double user = (u[2].QuadPart - u[0].QuadPart) / 10000000.0;
            double kernel = (u[3].QuadPart - u[1].QuadPart) / 10000000.0;
            return std::make_tuple(user, kernel);
        }
      private:
        FILETIME ft_[6];
    };
    
    
    class ScopedProcessorTimer
    {
      public:
        ScopedProcessorTimer(std::ostream& os = std::cerr) : timer_(ProcessorTimer()), os_(os) { }
        ~ScopedProcessorTimer()
        {
            std::tuple t = timer_.stop();
            os_ << "user " << std::get<0>(t) << "\n";
            os_ << "kernel " << std::get<1>(t) << "\n";
        }
      private:
        ProcessorTimer timer_;
        std::ostream& os_;
    }
    

    For example, one can measure how long it takes a block to execute, by defining a ScopedProcessorTimer at the beginning of that {} block.

提交回复
热议问题