Proper use of rospy.Rate or ros::Rate

Background

I created this topic because I frequently come across the use of rospy.Rate (ROS Python) and ros::Rate (ROS C++) in places where they are not needed.

By the way, what is this Rate thingy?

According to ROS Wiki, rospy.Rate and ros::Rate are convenience classes that make a best effort at maintaining a particular rate for a loop. For example:

// C++ example
ros::Rate r(10); // 10 hz
while (ros::ok())
{
  // ... do some work ...
  r.sleep();
}
# Python example
r = rospy.Rate(10) # 10Hz
while not rospy.is_shutdown():
  # ... do some work ...
  r.sleep()

In the above examples, the Rate instance will attempt to keep the loop at 10hz (10 loops per second) by accounting for the time used by the work done during the loop. The sleep() method is used for implementing the set Rate value.

So, what is the key point here?

Using the Rate object outside a loop is not proper. Only use it when you want to control how fast a loop executes.

3 Likes