Simple timer using C++11's chrono library

deceptikon 0 Tallied Votes 7K Views Share

No bells and whistles, just a quickie millisecond timer showing an alternative to the far less portable clock_t method. A test main() is included, just define TEST_DRIVER as a macro or remove the conditional compilation at the end.

#if __cplusplus < 201103L && (!defined(_MSC_VER) || _MSC_VER < 1700)
#error jrd::Timer class requires C++11 support
#else
#include <chrono>
#include <ostream>

namespace jrd {
    namespace time {
        class Timer {
            typedef std::chrono::high_resolution_clock high_resolution_clock;
            typedef std::chrono::milliseconds milliseconds;
        public:
            explicit Timer(bool run = false)
            {
                if (run)
                    Reset();
            }

            void Reset()
            {
                _start = high_resolution_clock::now();
            }

            milliseconds Elapsed() const
            {
                return std::chrono::duration_cast<milliseconds>(high_resolution_clock::now() - _start);
            }

            template <typename T, typename Traits>
            friend std::basic_ostream<T, Traits>& operator<<(std::basic_ostream<T, Traits>& out, const Timer& timer)
            {
                return out << timer.Elapsed().count();
            }
        private:
            high_resolution_clock::time_point _start;
        };
    }
}
#endif

#ifdef TEST_DRIVER

#include <iostream>

int main()
{
    jrd::time::Timer timer(true);

    // Kill some time
    for (int i = 0; i < 1000000000; i++)
        ;

    std::cout << "Elapsed time: " << std::fixed << timer << "ms\n";

    timer.Reset();

    // Kill some more time
    for (int i = 0; i < 10000000; i++)
        ;

    auto elapsed = timer.Elapsed();

    std::cout << "Elapsed time: " << std::fixed << elapsed.count() << "ms\n";
}

#endif
vijayan121 1,152 Posting Virtuoso
#include <chrono>
#include <type_traits>

struct timer
{
    typedef typename std::conditional< std::chrono::high_resolution_clock::is_steady,
                                       std::chrono::high_resolution_clock,
                                       std::chrono::steady_clock >::type clock_type ;

    // ...

    private: clock_type::time_point start_time /* = clock_type::now() */ ;
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.