When Programming with Time: A simple case of precision

Recently, I had a case in which I was dealing with time in a program. There are a few things to keep in mind when dealing with time, the articles below explain the complexities of programming with time well.

Photo by Kevin Ku on Unsplash

Recently, I was programming a feature related to time. We had a few outward interfaces (APIs) that we exposed for a couple of clients (software, not people or organizations 😉). The function of these clients differed and also the function of the APIs exposed.

During integration we ran into a glitch, an API in which we were providing the ETA in milliseconds to an event in the future. It was behaving differently than expected, leading to an invalid negative value. In modern software, race conditions can occur in milliseconds (or smaller time duration) and this was such a case. Below is some representational code to indicate what was occurring.

Representation program snippet.

When I ran the above code (Java 8) on tech.io, the output was something like this.

Output of the representation program.

You can try it out with this tech.io snippet.

In Cases 1 and 2, the duration are relatively larger at hours and seconds, and hence your precision is of low importance.

When you are dealing with duration that are near or lower than your expected precision, things go awry. You can see that in Case 3 (line 4) it is 0 millis, but in Case 4 (line 5) it is -682 millis.

You can see in the above example how the difference in precision can make things go unexpectedly. The problem in the end was similar to Case 4 was with our handling of precision. We had missed dealing with time with a consistent precision. Some APIs handled in seconds, some in milliseconds and in program it was left to Java default. Making the precision consistent ( to seconds) in the program if not the interface was sufficient to solve the issue.

Precision and accuracy are concepts from high school (physics), and even when measuring in programs these are as crucial as they are in the physical world. It was a learning moment for me, thought it is also one worth sharing🙂.

--

--