How the rospy.sleep and how the rospy.Rate() works

Hi, I would like to understand how exactly this rate.sleep() works in tandem with rospy.rate(). How these two are linked. I have attached the image and would like to know why we kept rate.sleep() inside the loop and what does it actually do. What if we increase the frequency in rospy.rate and how it affects our program. image In short I want to understand the mechanism of working. Thanks.

Please check the following post and let me know if it helps.

This answer is fair enough for rate but I am still bit confused about how the rate.sleep works in a loop. For instance if we kept while i< request.duration then then loop will continue until i becomes equal to request.duration but here my question is that rate.sleep() is inside the loop which means it is implemented every time the loop executes, then why does the robot stop when the i becomes equal to request.duration, is it like when the while loop becomes false, the rate.sleep() becomes true if I understood it correctly.

This is the “password” for how rospy.rate works:

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.

The rate.sleep() method (it is a method, not a variable) does not determine when the loop ends, only how fast it runs. Take for example:

rate = rospy.Rate(10)  # 10Hz: 10 times per second
while condition:
   do_some_work()
   rate.sleep()

Let’s assume that the imaginary function do_some_work() takes 0.05 seconds to run. Without rate.sleep(), the loop would run 20 times per second (while condition evaluates to True).

With rate.sleep(), however, the loop will run 10 times per second, as specified in the definition of rate. The “enforcer” method, rate.sleep(), does this by making the code pause (sleep) for an additional 0.05 seconds so that the total time spent is 0.10 seconds instead of 0.05.

PS: obviously we can only make the loop run slower than usual, not faster. If do_some_work() takes 0.20 seconds to run, the loop will run 5 times per second and the rate will be useless.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.