diff --git a/rclcpp/include/rclcpp/time.hpp b/rclcpp/include/rclcpp/time.hpp index 22e0335..e93cb64 100644 --- a/rclcpp/include/rclcpp/time.hpp +++ b/rclcpp/include/rclcpp/time.hpp @@ -102,6 +102,13 @@ public: rcl_time_point_value_t nanoseconds() const; + /// \return the seconds since epoch as a floating point number. + /// \warning Depending on sizeof(double) there could be significant precision loss. + /// When an exact time is required use nanoseconds() instead. + RCLCPP_PUBLIC + double + seconds() const; + RCLCPP_PUBLIC rcl_clock_type_t get_clock_type() const; diff --git a/rclcpp/src/rclcpp/time.cpp b/rclcpp/src/rclcpp/time.cpp index c22ec50..9ab924a 100644 --- a/rclcpp/src/rclcpp/time.cpp +++ b/rclcpp/src/rclcpp/time.cpp @@ -227,6 +227,12 @@ Time::nanoseconds() const return rcl_time_.nanoseconds; } +double +Time::seconds() const +{ + return std::chrono::duration(std::chrono::nanoseconds(rcl_time_.nanoseconds)).count(); +} + rcl_clock_type_t Time::get_clock_type() const { diff --git a/rclcpp/test/test_time.cpp b/rclcpp/test/test_time.cpp index 5a34d8b..6146efb 100644 --- a/rclcpp/test/test_time.cpp +++ b/rclcpp/test/test_time.cpp @@ -244,3 +244,9 @@ TEST(TestTime, overflows) { rclcpp::Time two_time(2); EXPECT_NO_THROW(one_time - two_time); } + +TEST(TestTime, seconds) { + EXPECT_DOUBLE_EQ(0.0, rclcpp::Time(0, 0).seconds()); + EXPECT_DOUBLE_EQ(4.5, rclcpp::Time(4, 500000000).seconds()); + EXPECT_DOUBLE_EQ(2.5, rclcpp::Time(0, 2500000000).seconds()); +}