// posix_2001_cpu_timer.hpp // Copyright by Yuriy Koblents-Mishke, 2007. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) /// ??? // See http://www.?????? for documentation. #ifndef BOOST_POSIX_2001_CPU_TIMER_HPP #define BOOST_POSIX_2001_CPU_TIMER_HPP #include // BOOST_TYPEOF namespace boost { namespace detail { namespace { #include #include } // to not pollute ::boost::detail by symbols defined in the above headers class cpu_timer_impl // implementation of cpu_timer { private: typedef struct rusage CPUclock; // kernel, user CPUclock start_clock_; static const size_t clock_per_sec_ = 1000000; // 1 us = 1/millionths of a second static const CPUclock get_cpu_time(); public: cpu_timer_impl(); // sets cpu() to zero void restart(); // resets cpu() to zero double cpu() const; // returns CPU time in seconds double cpu_max() const; // maximum possible value for cpu() double cpu_min() const // minimum possible value for cpu() { return double(1)/double(clock_per_sec_); } }; // cpu_timer_impl inline const cpu_timer_impl::CPUclock cpu_timer_impl::get_cpu_time() { CPUclock current_clock; getrusage(RUSAGE_SELF, & current_clock ); return current_clock; } inline cpu_timer_impl::cpu_timer_impl() : start_clock_( get_cpu_time() ){} inline void cpu_timer_impl::restart() { start_clock_ = get_cpu_time(); } inline double cpu_timer_impl::cpu_max() const // maximum possible value for cpu() { typedef BOOST_TYPEOF(start_clock_.ru_utime.tv_sec) ru_uint; return double( (::std::numeric_limits::max)() - start_clock_.ru_utime.tv_sec // seconds - start_clock_.ru_stime.tv_sec ) - ( double(start_clock_.ru_utime.tv_usec) // microseconds + double(start_clock_.ru_stime.tv_usec) ) / double(clock_per_sec_); } inline double cpu_timer_impl::cpu() const { const CPUclock current_clock = get_cpu_time(); return ( double( current_clock.ru_utime.tv_usec ) // microseconds - double( start_clock_.ru_utime.tv_usec ) // avoid substraction + double( current_clock.ru_stime.tv_usec ) // of unsigned: - double( start_clock_.ru_stime.tv_usec ) ) // may wrap around! / clock_per_sec_ + double( current_clock.ru_utime.tv_sec // seconds - start_clock_.ru_utime.tv_sec ) // with whole seconds + double( current_clock.ru_stime.tv_sec // the substraction - start_clock_.ru_stime.tv_sec ); // is not dangerous // because counters do not // wrap around on overflow } }} // namespace boost::detail #endif // BOOST_POSIX_2001_CPU_TIMER_HPP guard