time_utils.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include "common/time_utils.hpp"
  2. #include <iomanip>
  3. #include <sstream>
  4. #include <iostream>
  5. namespace smartbotic::common {
  6. int64_t TimeUtils::nowMs() {
  7. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8. Clock::now().time_since_epoch()
  9. ).count();
  10. }
  11. int64_t TimeUtils::nowSec() {
  12. return std::chrono::duration_cast<std::chrono::seconds>(
  13. Clock::now().time_since_epoch()
  14. ).count();
  15. }
  16. TimeUtils::TimePoint TimeUtils::now() {
  17. return Clock::now();
  18. }
  19. TimeUtils::TimePoint TimeUtils::fromMs(int64_t ms) {
  20. return TimePoint(std::chrono::milliseconds(ms));
  21. }
  22. int64_t TimeUtils::toMs(TimePoint tp) {
  23. return std::chrono::duration_cast<std::chrono::milliseconds>(
  24. tp.time_since_epoch()
  25. ).count();
  26. }
  27. std::string TimeUtils::toIso8601(int64_t ms) {
  28. return toIso8601(fromMs(ms));
  29. }
  30. std::string TimeUtils::toIso8601(TimePoint tp) {
  31. auto time = Clock::to_time_t(tp);
  32. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  33. tp.time_since_epoch()
  34. ).count() % 1000;
  35. std::tm tm{};
  36. gmtime_r(&time, &tm);
  37. std::ostringstream ss;
  38. ss << std::put_time(&tm, "%Y-%m-%dT%H:%M:%S")
  39. << '.' << std::setfill('0') << std::setw(3) << ms << 'Z';
  40. return ss.str();
  41. }
  42. int64_t TimeUtils::parseIso8601(const std::string& str) {
  43. std::tm tm{};
  44. int ms = 0;
  45. std::istringstream ss(str);
  46. ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%S");
  47. if (ss.peek() == '.') {
  48. ss.ignore();
  49. ss >> ms;
  50. }
  51. auto time = timegm(&tm);
  52. return static_cast<int64_t>(time) * 1000 + ms;
  53. }
  54. bool TimeUtils::isExpired(int64_t expiryMs) {
  55. return nowMs() > expiryMs;
  56. }
  57. bool TimeUtils::isExpired(TimePoint expiry) {
  58. return now() > expiry;
  59. }
  60. int64_t TimeUtils::addMs(int64_t timestampMs, int64_t durationMs) {
  61. return timestampMs + durationMs;
  62. }
  63. int64_t TimeUtils::addSec(int64_t timestampMs, int64_t durationSec) {
  64. return timestampMs + (durationSec * 1000);
  65. }
  66. // ScopedTimer implementation
  67. ScopedTimer::ScopedTimer(const std::string& name)
  68. : name_(name), start_(TimeUtils::now()) {}
  69. ScopedTimer::~ScopedTimer() {
  70. if (!name_.empty()) {
  71. std::cout << "[Timer] " << name_ << ": " << elapsedMs() << "ms" << std::endl;
  72. }
  73. }
  74. int64_t ScopedTimer::elapsedMs() const {
  75. return TimeUtils::toMs(TimeUtils::now()) - TimeUtils::toMs(start_);
  76. }
  77. void ScopedTimer::reset() {
  78. start_ = TimeUtils::now();
  79. }
  80. } // namespace smartbotic::common