r/cpp • • Mar 16 '26

Circular Distance

https://biowpn.github.io/bioweapon/2026/03/14/circular-distance.html
33 Upvotes

17 comments sorted by

View all comments

Show parent comment

3

u/TheThiefMaster C++latest fanatic (and game dev) Mar 16 '26

I have a function that sorts timestamps in a scheduler, taking wrapping into account.

It works by subtracting each timestamp from "now" and then comparing them. Essentially sorting them by "closest to now" rather than absolute value.

It compiles into three subtractions (because a less-than is a subtraction):

bool compare_timestamps(uint32 a, uint32 b)
{
    return (a-now)<(b-now);
}

The timestamps do move fast enough that 32 bit wrapping is likely. I could use 64-bit which wouldn't wrap within the lifespan of our civilization but where's the fun in that?

2

u/TheMania Mar 17 '26

The more idiomatic way for comparing timestamps is just:

(int32)(a-b) < 0

Provided they each differ by less than half the unsigned range it produces correct results. And if they differ by more than that, you really need a wider type :)