Potential issue with TICKS_DIFF macro #10723
-
While browsing the source code to see how the system timer of the RP2 is used, I stumbled by chance on the TICKS_DIFF macro of softtimer.c:
I presume it is meant to calculate the relative difference between two values to determine when a timeout has occurred. Assuming that is true, it seemed more complicated than it should be, and something like this should work as well:
The above uses properties of binary numbers and two's complement arithmetic. I adapted a test code I made in the past to compare the results of two different ways to calculate the same thing:
The code above is compiled with gcc. It exercises some borderline conditions, such as values close to UINT32_MAX/2 when the signal bit of an int32_t changes and UINT32_MAX when the counter rolls over. In all these cases, both macros produce the same results. Here is the results I obtained:
In all cases, the difference is close to UINT32_MAX/2 so the probability of them to occur is extremely low. I added the two lines below to the test vector
which produced the following result:
So with a difference of UINT32_MAX/4, which is still pretty big, things work as expected. One suggestion: use inline static instead of macros:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
The Macro you mention is only used in softtimer.c, with similar code being used for the ticks_diff() method of the time module, where the sign of the result matters. I do not understand why you suggest using a method which will produce wrong results under certain conditions, even if these seem rare. Sooner or later this will be an issue, latest after ~25 days, since it is used tick the ticks_ms counter. |
Beta Was this translation helpful? Give feedback.
-
This is to mark the thread as answered based on @jimmo 's first answer above. |
Beta Was this translation helpful? Give feedback.
This is to mark the thread as answered based on @jimmo 's first answer above.