Skip to content

Instantly share code, notes, and snippets.

@bigdavedev
Created August 26, 2016 04:29
Show Gist options
  • Save bigdavedev/c9d745d188ea6c714c3b2918a6be1e42 to your computer and use it in GitHub Desktop.
Save bigdavedev/c9d745d188ea6c714c3b2918a6be1e42 to your computer and use it in GitHub Desktop.
posix chrono casting
#include <chrono>
#include <iostream>
#include <system_error>
#include <ctime>
using namespace std::chrono_literals;
namespace std
{
namespace chrono
{
namespace detail
{
template<typename From, typename To>
struct posix_time_point_cast;
template<typename Clock, typename Duration>
struct posix_time_point_cast<std::chrono::time_point<Clock, Duration>, timespec>
{
static timespec cast(std::chrono::time_point<Clock, Duration> time_point)
{
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(time_point.time_since_epoch());
timespec result{ seconds.count(), 0 };
return std::move(result);
}
};
template<typename Clock, typename Duration>
struct posix_time_point_cast<timespec, std::chrono::time_point<Clock, Duration>>
{
static timespec cast(timespec spec)
{
auto duration = seconds{ spec.tv_sec } + nanoseconds{ spec.tv_nsec };
time_point<Clock, Duration> time = duration_cast<Duration>(duration);
return std::move(time);
}
};
} // detail
template<typename T, typename Clock, typename Duration>
auto time_point_cast(time_point<Clock, Duration> point) -> std::enable_if_t<std::is_same<T, timespec>::value, timespec>
{
return detail::posix_time_point_cast<time_point<Clock, Duration>, timespec>::cast(point);
}
template<typename TimePoint>
TimePoint time_point_cast(timespec spec)
{
return detail::posix_time_point_cast<timespec, TimePoint>::cast(spec);
}
}
}
auto getSystemTime()
{
return std::chrono::system_clock::now();
}
void setSystemTime(std::chrono::system_clock::time_point timePoint)
{
auto time = std::chrono::time_point_cast<timespec>(timePoint);
std::cout << time.tv_sec << std::endl;
if (clock_settime(CLOCK_REALTIME, &time) != 0)
{
throw std::system_error(errno, std::system_category());
}
}
int main(int argc, char* argv[])
{
auto now = getSystemTime();
timespec ts = std::chrono::time_point_cast<timespec>(now);
std::chrono::system_clock::time_point tp = std::chrono::time_point_cast<std::chrono::system_clock::time_point>(ts);
setSystemTime(now);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment