| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- #include "common/time_utils.hpp"
- #include <iomanip>
- #include <sstream>
- #include <iostream>
- namespace smartbotic::common {
- int64_t TimeUtils::nowMs() {
- return std::chrono::duration_cast<std::chrono::milliseconds>(
- Clock::now().time_since_epoch()
- ).count();
- }
- int64_t TimeUtils::nowSec() {
- return std::chrono::duration_cast<std::chrono::seconds>(
- Clock::now().time_since_epoch()
- ).count();
- }
- TimeUtils::TimePoint TimeUtils::now() {
- return Clock::now();
- }
- TimeUtils::TimePoint TimeUtils::fromMs(int64_t ms) {
- return TimePoint(std::chrono::milliseconds(ms));
- }
- int64_t TimeUtils::toMs(TimePoint tp) {
- return std::chrono::duration_cast<std::chrono::milliseconds>(
- tp.time_since_epoch()
- ).count();
- }
- std::string TimeUtils::toIso8601(int64_t ms) {
- return toIso8601(fromMs(ms));
- }
- std::string TimeUtils::toIso8601(TimePoint tp) {
- auto time = Clock::to_time_t(tp);
- auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
- tp.time_since_epoch()
- ).count() % 1000;
- std::tm tm{};
- gmtime_r(&time, &tm);
- std::ostringstream ss;
- ss << std::put_time(&tm, "%Y-%m-%dT%H:%M:%S")
- << '.' << std::setfill('0') << std::setw(3) << ms << 'Z';
- return ss.str();
- }
- int64_t TimeUtils::parseIso8601(const std::string& str) {
- std::tm tm{};
- int ms = 0;
- std::istringstream ss(str);
- ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%S");
- if (ss.peek() == '.') {
- ss.ignore();
- ss >> ms;
- }
- auto time = timegm(&tm);
- return static_cast<int64_t>(time) * 1000 + ms;
- }
- bool TimeUtils::isExpired(int64_t expiryMs) {
- return nowMs() > expiryMs;
- }
- bool TimeUtils::isExpired(TimePoint expiry) {
- return now() > expiry;
- }
- int64_t TimeUtils::addMs(int64_t timestampMs, int64_t durationMs) {
- return timestampMs + durationMs;
- }
- int64_t TimeUtils::addSec(int64_t timestampMs, int64_t durationSec) {
- return timestampMs + (durationSec * 1000);
- }
- // ScopedTimer implementation
- ScopedTimer::ScopedTimer(const std::string& name)
- : name_(name), start_(TimeUtils::now()) {}
- ScopedTimer::~ScopedTimer() {
- if (!name_.empty()) {
- std::cout << "[Timer] " << name_ << ": " << elapsedMs() << "ms" << std::endl;
- }
- }
- int64_t ScopedTimer::elapsedMs() const {
- return TimeUtils::toMs(TimeUtils::now()) - TimeUtils::toMs(start_);
- }
- void ScopedTimer::reset() {
- start_ = TimeUtils::now();
- }
- } // namespace smartbotic::common
|