Performance: When to use services vs topics
This concept affects the responsiveness and efficiency of communication in a ROS system, impacting how quickly and reliably data is exchanged between nodes.
ros::Subscriber sub = nh.subscribe("/camera/image", 10, imageCallback); // subscribing to topic for continuous image stream
ros::ServiceClient client = nh.serviceClient<sensor_msgs::GetImage>("/camera/image");
// repeatedly calling service to get image data| Pattern | Message Frequency | Blocking Behavior | Resource Usage | Verdict |
|---|---|---|---|---|
| Service for continuous data | High | Blocks caller until response | High CPU and network load | [X] Bad |
| Topic for continuous data | High | Non-blocking asynchronous | Efficient CPU and network use | [OK] Good |
| Topic for infrequent requests | Low | Non-blocking but unnecessary messages | Wastes resources | [!] Bad |
| Service for infrequent requests | Low | Blocks only during call | Minimal resource use | [OK] Good |
service instead of a topic?rospy.ServiceProxy with the service name and type.rospy.Service defines a service server, rospy.Subscriber subscribes to topics, and rospy.Publisher publishes to topics.import rospy
from std_srvs.srv import SetBool
def call_service():
rospy.wait_for_service('toggle_led')
try:
toggle_led = rospy.ServiceProxy('toggle_led', SetBool)
response = toggle_led(True)
print(response.success)
except rospy.ServiceException as e:
print('Service call failed:', e)
call_service()response.success will be True or False depending on service logic; if it fails, an exception message prints.Pass the test and this pattern moves unknown