For more obvious cases eg. clock time is 12:05 and present time is 12:00, we don't have to think too hard to decide which direction to take the second hand to match up the two times.
However, suppose the clock time is currently 12:00, and the present time is 6:00. We can move the second hand forward 8x, or backwards 4x. Which direction will result in quicker synchronization of the 2 times?
For both directions, the number of seconds to traverse is 6 x 60 x 60 = 21600 seconds.
If we take the forward direction, the time taken to traverse half the number of seconds i.e. 10800 is 1350 seconds. However, in that time, the present time would have advanced by the same amount, so the number of seconds left to traverse would be 10800 + 1350 = 12150 seconds. If we do this iteratively, we would find the total time required to achieve synchronization is 3085 seconds, with 4 seconds left to catch up.
If we take the reverse direction, the time taken to traverse half would be 10800 / 4 = 2700 seconds. However, the present time would have advanced by the same amount, so the number of seconds left to traverse would be 10800 - 2700 = 8100 seconds. If we do this iteratively, the total time required to achieve synchronization is 4320 seconds, with 1 second left to catch up.
So in this case, traversing in the forward direction will result in quicker synchronization.
The Python code for performing this calculation is:
With a little trial and eror, I can determine that the dividing line is when fwd_duration = 7*60*60+2 = 25202 eg. when clock time is 4:59:58 and needs to sync to 12:00:00. The forward and reverse timing in this case are both exactly 3600 secs i.e. exactly 1 hour.
So in my clock logic, I can decide to move the second hand forward if fwd_duration < 25202, and go in reverse if fwd_duration >= 25202.
The logic to calculate the fwd_duration between 2 times (hh1:mm1:ss1) and (hh2:mm1:ss2) is:
However, as the ULP is 16-bit, signed number range between -32767 and 32768, so the above operation is out of range (12*60*60 = 43200), unless we cook up some 32-bit integer math code.
Another way is decompose everything into even simpler operations:
time_diff() is able to compute fwd_duration in [hh, mm, ss] format.
time_less_than() tells you whether one duration given in [hh, mm, ss] format is less than another. Our previous threshold of 25202 secs is [7, 0, 2] in [hh, mm, ss] format.