timemeasurement.h 1.46 KB
#ifndef OSDEV_COMPONENTS_MQTT_MEASUREMENT_TIMEMEASUREMENT_H
#define OSDEV_COMPONENTS_MQTT_MEASUREMENT_TIMEMEASUREMENT_H

#include <chrono>
#include <functional>
#include <ostream>
#include <string>

namespace osdev {
namespace components {
namespace mqtt {
namespace measurement {

using TimeMeasurementCallback = std::function<void(const std::string& id, std::chrono::steady_clock::time_point start, std::chrono::microseconds sinceStart, std::chrono::microseconds sinceLast)>;

class TimeMeasurement
{
public:
    TimeMeasurement(const std::string& id, const TimeMeasurementCallback& callback, bool measureOnDestruction = true);
    ~TimeMeasurement();

    TimeMeasurement(const TimeMeasurement&) = delete;
    TimeMeasurement& operator=(const TimeMeasurement&) = delete;
    TimeMeasurement(TimeMeasurement&&) = default;
    TimeMeasurement& operator=(TimeMeasurement&&) = default;

    void set();
    void measure();

private:
    std::string m_id;

    std::chrono::steady_clock::time_point m_start;
    std::chrono::steady_clock::time_point m_last;
    TimeMeasurementCallback m_callback;
    bool m_measureOnDestruction;
};

template <typename Rep, typename Dur>
std::ostream& operator<<(std::ostream& os, const std::chrono::duration<Rep, Dur>& rhs)
{
    os << rhs.count();
    return os;
}

}       // End namespace measurement
}       // End namespace mqtt
}       // End namespace components
}       // End namespace osdev

#endif  // OSDEV_COMPONENTS_MQTT_MEASUREMENT_TIMEMEASUREMENT_H