C++ Libraries/chrono High Resolution Clock

From Software Engineers Wiki
Jump to: navigation, search

How to use high resolution clock?

Answer

Use std::chrono::high_resolution_clock.

std::chrono::high_resolution_clock::now() can be used to get current timestamp.

#include <chrono>

class CProfile {
private:
        std::chrono::high_resolution_clock::time_point m_start, m_stop;
public:
        CProfile() {}
        void start(void) { m_start = std::chrono::high_resolution_clock::now(); }
        void stop(void) { m_stop = std::chrono::high_resolution_clock::now(); }
        double getSeconds(void) {
                std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(m_stop - m_start);
                return time_span.count();
        }
        unsigned long getMS(void) {
                std::chrono::milliseconds time_span = std::chrono::duration_cast<std::chrono::milliseconds>(m_stop - m_start);
                return time_span.count();
        }
        unsigned long getUS(void) {
                std::chrono::microseconds time_span = std::chrono::duration_cast<std::chrono::microseconds>(m_stop - m_start);
                return time_span.count();
        }
};

Test program:

#include <iostream>
#include <unistd.h>

int main(void)
{       
        CProfile pf;
        pf.start();
        usleep(100);
        pf.stop();

        std::cout << pf.getSeconds() << " seconds\n";

        return 0;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox