当前位置:网站首页>Ros2 method of obtaining current system time
Ros2 method of obtaining current system time
2022-07-26 21:18:00 【Shoufei loves playing with robots】
C++ Three kinds of clocks in the standard library
std::chrono::system_clock
using namespace std::chrono_literals;
const auto start = std::chrono::system_clock::now();
#include <iostream>
#include <iomanip>
#include <vector>
#include <numeric>
#include <chrono>
volatile int sink;
int main()
{
std::cout << std::fixed << std::setprecision(9) << std::left;
for (auto size = 1ull; size < 1000'000'000ull; size *= 100) {
// record start time
auto start = std::chrono::system_clock::now();
// do some work
std::vector<int> v(size, 42);
sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect
// record end time
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << "Time to fill and iterate a vector of " << std::setw(9)
<< size << " ints : " << diff.count() << " s\n";
}
}
/* Output Time to fill and iterate a vector of 1 ints : 0.000006568 s Time to fill and iterate a vector of 100 ints : 0.000002854 s Time to fill and iterate a vector of 10000 ints : 0.000116290 s Time to fill and iterate a vector of 1000000 ints : 0.011742752 s Time to fill and iterate a vector of 100000000 ints : 0.505534949 s */
//https://en.cppreference.com/w/cpp/chrono/system_clock/now
system_clock It is a system wide clock . It is modifiable . For example, synchronize network time . So the time difference of the system may be inaccurate .
std::chrono::steady_clock
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
int main()
{
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now - std::chrono::hours(24));
std::cout << "24 hours ago, the time was "
<< std::put_time(std::localtime(&now_c), "%F %T") << '\n';
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::cout << "Hello World\n";
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::cout << "Printing took "
<< std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
<< "us.\n";
}
/* Output 24 hours ago, the time was 2011-10-25 12:00:08 Hello World Printing took 84us. */
https://www.apiref.com/cpp-zh/cpp/chrono/time_point.html
steady_clock It's a monotonous clock . At this time, the time of the clock cannot be reduced , Like a physical stopwatch . Usually the accuracy can reach the nanosecond level , Suitable for calculating Program execution time .
std::chrono::high_resolution_clock
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
int main ()
{
using namespace std::chrono;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
std::cout << "printing out 1000 stars...\n";
for (int i=0; i<1000; ++i) std::cout << "*";
std::cout << std::endl;
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
std::cout << "It took me " << time_span.count() << " seconds.";
std::cout << std::endl;
return 0;
}
/* Output printing out 1000 stars... ******************************************************************************** ******************************************************************************** ******************************************************************************** ******************************************************************************** ******************************************************************************** ******************************************************************************** ******************************************************************************** ******************************************************************************** ******************************************************************************** ******************************************************************************** ******************************************************************************** ******************************************************************************** **************************************** It took me 0.091001 seconds. */
// Reference resources :https://cplusplus.com/reference/chrono/high_resolution_clock/now/
high_resolution_clock There are different implementations between different standard libraries .
Usually it's just std::chrono::steady_clock or std::chrono::system_clock Another name for , But the actual one depends on the library or configuration . For example, for gcc Of libstdc++ It is system_clock , about MSVC It is steady_clock , And for clang Of libc++ It depends on the configuration .
Therefore, it is recommended to directly use the corresponding clock instead of high_resolution_clock.
ROS2 Timestamp in
ROS2 Three kinds of clocks are defined in . The default is to use RCL_SYSTEM_TIME. It and C++ Medium std::chrono::system_clock It's the same , System time .
typedef enum rcl_clock_type_t
{
/// Clock uninitialized
RCL_CLOCK_UNINITIALIZED = 0,
/// Use ROS time
RCL_ROS_TIME,
/// Use system time
RCL_SYSTEM_TIME,
/// Use a steady clock time
RCL_STEADY_TIME
} rcl_clock_type_t;
ROS2 There are two kinds of timestamp in . One is the actual physical system time , The other is simulation time . The simulation time is usually Gazebo Emitted /clock topic of conversation .
/clock topic of conversation
clock:
sec: 65
nanosec: 212000000
---
clock:
sec: 65
nanosec: 298000000
---
clock:
sec: 65
nanosec: 388000000
When you need to test a program in a simulation environment , To put use_sim_time Set as True. Otherwise, the following error message will appear . Indicates that the time does not match .tf The relationship cannot be found normally .
Error message :
[controller_server]: Extrapolation Error: Lookup would require extrapolation into the future. Requested time 1646190408.221065 but the latest data is at time 19.413000, when looking up transform from frame [map] to frame [odom]
Set up use_sim_time It can be written in launch In file . As shown below :
def generate_launch_description():
use_sim_time = LaunchConfiguration('use_sim_time', default='false')
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value=use_sim_time,
description='Use simulation (Gazebo) clock if true'),
Node(
package='time_api_test',
executable='time_api_test',
parameters=[{
'use_sim_time': use_sim_time}],
arguments=[],
output='screen'),
])
stay ROS2 Get the current timestamp
The following code snippet lists several ways to get the system time :
auto t = rclcpp::Clock().now();
RCLCPP_INFO(this->get_logger(), "[rclcpp::Clock().now()] sec:%lf nano:%ld", t.seconds(), t.nanoseconds());
auto t1 = std::chrono::system_clock::now();
time_t tt = std::chrono::system_clock::to_time_t ( t1 );
RCLCPP_INFO(this->get_logger(), "[std::chrono::system_clock::now()] sec:%ld", tt);
std::chrono::steady_clock::time_point td = std::chrono::steady_clock::now();
std::chrono::steady_clock::duration dtn = td.time_since_epoch();
double secs = dtn.count() * std::chrono::steady_clock::period::num / std::chrono::steady_clock::period::den;
RCLCPP_INFO(this->get_logger(), "[std::chrono::steady_clock::now()] sec:%lf", secs);
auto t2 = this->get_clock()->now();
RCLCPP_INFO(this->get_logger(), "[get_clock()->now()] sec:%lf nano:%ld", t2.seconds(), t2.nanoseconds());
auto t3 = this->now();
RCLCPP_INFO(this->get_logger(), "[this->now()] sec:%lf nano:%ld", t3.seconds(), t3.nanoseconds());
Be careful , The complete sample code can be found in official account 《 First flight 》 In reply to “time” Get .
When use_sim_time by false when , The result of running the above test code is :
[time_api_test-1] [INFO 1658498046.378262276] [time_api_test]: [rclcpp::Clock().now()] sec:1658498046.378260 nano:1658498046378260389
[time_api_test-1] [INFO 1658498046.378315552] [time_api_test]: [std::chrono::system_clock::now()] sec:1658498046
[time_api_test-1] [INFO 1658498046.378325479] [time_api_test]: [std::chrono::steady_clock::now()] sec:5906.000000
[time_api_test-1] [INFO 1658498046.378333539] [time_api_test]: [get_clock()->now()] sec:1658498046.378333 nano:1658498046378333309
[time_api_test-1] [INFO 1658498046.378341987] [time_api_test]: [this->now()] sec:1658498046.378342 nano:1658498046378341769
You can find ,rclcpp::Clock().now(),get_clock()->now() and this->now() The time obtained is the same as std::chrono::system_clock::now() It's consistent .
Need here One thing to note is ,rclcpp::Clock().now(),get_clock()->now() and this->now() The obtained timestamp contains sec and nanosec.sec and nanosec Both describe the current time , It is equivalent. , But the units are different . One is in seconds , One is in nanoseconds .
When use_sim_time by true when , The result of running the above test code is :
Be careful , Before running the test code . I ran turtlebot3 Of gazebo Simulation environment . So that there are /clock Topic to provide simulation time .
[time_api_test-1] [INFO 1658498456.593959180] [time_api_test]: [rclcpp::Clock().now()] sec:1658498456.593951 nano:1658498456593951346
[time_api_test-1] [INFO 1658498456.594114487] [time_api_test]: [std::chrono::system_clock::now()] sec:1658498456
[time_api_test-1] [INFO 1658498456.594132577] [time_api_test]: [std::chrono::steady_clock::now()] sec:6316.000000
[time_api_test-1] [INFO 1658498456.594142330] [time_api_test]: [get_clock()->now()] sec:300.636000 nano:300636000000
[time_api_test-1] [INFO 1658498456.594149351] [time_api_test]: [this->now()] sec:300.636000 nano:300636000000
You can see ,rclcpp::Clock().now() Or with std::chrono::system_clock::now() bring into correspondence with . explain rclcpp::Clock().now() Simulation time cannot be returned .
get_clock()->now() and this->now() It's equivalent . They all returned the simulation time .
After testing and comparison , It can be concluded that ,rclcpp::Clock().now() Unable to get the simulation time correctly . So when you want to get the timestamp in the code , Callable get_clock()->now() and this->now() Interface . This ensures that the flag bit use_sim_time When the change , The timestamps used throughout the code are consistent .
Method of calculating program running time
rclcpp::Clock steady_clock_{RCL_STEADY_TIME};
auto start_time = steady_clock_.now();
//do something ...
auto cycle_duration = steady_clock_.now() - start_time;
RCLCPP_INFO(get_logger(), "Cost %.4f s", cycle_duration.seconds());
Use RCL_STEADY_TIME The clock is more accurate to calculate the running time of the program .
If you think it's useful, just praise it !
It's me , One to help everyone Filling pit Robot development siege lion .
In addition, the official account. 《 First flight 》 Internal reply “ robot ” Get carefully recommended C/C++,Python,Docker,Qt,ROS1/2 And other commonly used technical data in the robot industry .
边栏推荐
- [question] browser get request with token
- After chatting with byte programmers with a monthly salary of 3W, I realized that I had been doing chores
- There are six ways to help you deal with the simpledateformat class, which is not a thread safety problem
- JDBC的连接
- [pytoch foundation] torch.stack() function analysis
- CONDA reports an error: json.decoder.jsondecodeerror:
- Leetcode linked list problem - 19. Delete the penultimate node of the linked list (learn the linked list with one question and one article)
- GOM and GEE lander list file encryption tutorial
- flask 源码梗概
- 2022 open atom global open source summit agenda express | list of sub forum agenda on July 27
猜你喜欢

【HCIA安全】双向NAT

2022开放原子全球开源峰会议程速递 | 7 月 27 日分论坛议程一览

Today, the company came across an Alibaba P8, which was really seen as the ceiling of the foundation

Flash source code outline
![[download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng](/img/62/9e2ff0dc2c8b049fd32ad56334a0c0.jpg)
[download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng
![[OBS] solve the problem of OBS pushing two RTMP streams + timestamp](/img/71/dbd00f69251b96b0e56de399103f72.png)
[OBS] solve the problem of OBS pushing two RTMP streams + timestamp

Error in render: “TypeError: data.slice is not a function“
![[Oracle training] - deploy Ogg known as zero downtime migration](/img/bc/4ee0493129d5abab931ca50dbdce6f.png)
[Oracle training] - deploy Ogg known as zero downtime migration
![[JVM series] JVM tuning](/img/6b/f7c402b2ff5fc4f11f9656a7a59873.png)
[JVM series] JVM tuning

flask 源码梗概
随机推荐
【HCIA安全】双向NAT
【HCIA安全】NAT网络地址转换
Browser browser cache
银河证券场内基金低佣金开户靠谱吗,可靠安全吗
基于Hough变换的直线检测(Matlab)
In the era of Web3.0, the technical theory of implementing a DAPP based on P2P DB
Flash source code outline
Flutter性能优化实践 —— UI篇
What kind of security problems will the server encounter?
QT基础第一天 (1)QT,GUI(图形用户接口)开发
GOM跟GEE登陆器列表文件加密教程
idea中检索此方法中有哪些参数以便我们使用——1.类图。2.双击shift
After chatting with byte programmers with a monthly salary of 3W, I realized that I had been doing chores
Redis interview questions
Swiftui 4's new function of real-time access to click location.Ontapgeture {location in} (tutorial with source code)
Deployment of kubernetes
2022-7-26 the seventh group of abstractions and interfaces
[MySQL series] - how much do you know about the index
Web3.0 时代,基于P2PDB实现一款Dapp的技术理论
TableWidget