ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A
Ask Your Question
0 sometimes returns 0.

asked 2021-10-14 05:42:46 -0500

Roshan gravatar image

updated 2021-10-14 11:38:12 -0500

Mike Scheutzow gravatar image

Hello, I'm trying to run this code:

  prevTime =
    while not rospy.is_shutdown():
            currentTime =

            delT = currentTime-prevTime

            print("Previous time:",prevTime.to_sec())
            print("Current time",currentTime.to_sec())


to get the time of the while loop, because I have a function of time that needs it. Sometimes when running this, prevTime becomes 0:

Previous time: 0.0
Current time 1266.097
Time: 1266.097
Previous time: 0.0
Current time 1266.107
Time: 1266.107
Previous time: 0.0
Current time 1266.117
Time: 1266.117
Previous time: 0.0
Current time 1266.127
Time: 1266.127

And other times it works as intended:

Previous time: 1263.221
Current time 1263.321
Time: 0.1
Previous time: 1263.221
Current time 1263.331
Time: 0.11
Previous time: 1263.221
Current time 1263.341
Time: 0.12
Previous time: 1263.221
Current time 1263.351
Time: 0.13

Wondering what the issue could be, and how to stop it from becoming 0

edit retag flag offensive close merge delete


Are you using simulated time?

tryan gravatar image tryan  ( 2021-10-14 08:29:00 -0500 )edit

Yes, running the simluations in Gazebo

Roshan gravatar image Roshan  ( 2021-10-14 08:34:51 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2021-10-14 08:53:37 -0500

tryan gravatar image

prevTime may sometimes initialize before the first /clock message, so it defaults to 0. If you use a non-deterministic method of starting nodes, e.g., roslaunch, the startup order can vary, so this will happen sometimes but not others. As noted in the rospy Time overview, one workaround is to loop the assignment until it returns a non-zero value:

prevTime = 0
while not prevTime:
    prevTime =
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2021-10-14 05:42:46 -0500

Seen: 201 times

Last updated: Oct 14 '21