time_utils.hpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #pragma once
  2. #include <chrono>
  3. #include <string>
  4. #include <ctime>
  5. namespace smartbotic::common {
  6. class TimeUtils {
  7. public:
  8. using Clock = std::chrono::system_clock;
  9. using TimePoint = Clock::time_point;
  10. using Duration = Clock::duration;
  11. // Get current timestamp in milliseconds
  12. static int64_t nowMs();
  13. // Get current timestamp in seconds
  14. static int64_t nowSec();
  15. // Get current timestamp as TimePoint
  16. static TimePoint now();
  17. // Convert milliseconds to TimePoint
  18. static TimePoint fromMs(int64_t ms);
  19. // Convert TimePoint to milliseconds
  20. static int64_t toMs(TimePoint tp);
  21. // Format timestamp as ISO 8601 string
  22. static std::string toIso8601(int64_t ms);
  23. static std::string toIso8601(TimePoint tp);
  24. // Parse ISO 8601 string to milliseconds
  25. static int64_t parseIso8601(const std::string& str);
  26. // Check if timestamp has expired
  27. static bool isExpired(int64_t expiryMs);
  28. static bool isExpired(TimePoint expiry);
  29. // Add duration to timestamp
  30. static int64_t addMs(int64_t timestampMs, int64_t durationMs);
  31. static int64_t addSec(int64_t timestampMs, int64_t durationSec);
  32. };
  33. // RAII timer for measuring durations
  34. class ScopedTimer {
  35. public:
  36. explicit ScopedTimer(const std::string& name = "");
  37. ~ScopedTimer();
  38. int64_t elapsedMs() const;
  39. void reset();
  40. private:
  41. std::string name_;
  42. TimeUtils::TimePoint start_;
  43. };
  44. } // namespace smartbotic::common