Add rclcpp::Time::seconds() (#526)

* Get seconds since epoch as double
This commit is contained in:
Shane Loretz 2018-08-08 16:04:35 -07:00 committed by GitHub
parent 4ddb76f466
commit ea047655d8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 0 deletions

View file

@ -102,6 +102,13 @@ public:
rcl_time_point_value_t rcl_time_point_value_t
nanoseconds() const; 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 RCLCPP_PUBLIC
rcl_clock_type_t rcl_clock_type_t
get_clock_type() const; get_clock_type() const;

View file

@ -227,6 +227,12 @@ Time::nanoseconds() const
return rcl_time_.nanoseconds; return rcl_time_.nanoseconds;
} }
double
Time::seconds() const
{
return std::chrono::duration<double>(std::chrono::nanoseconds(rcl_time_.nanoseconds)).count();
}
rcl_clock_type_t rcl_clock_type_t
Time::get_clock_type() const Time::get_clock_type() const
{ {

View file

@ -244,3 +244,9 @@ TEST(TestTime, overflows) {
rclcpp::Time two_time(2); rclcpp::Time two_time(2);
EXPECT_NO_THROW(one_time - two_time); 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());
}