Fast UID algorithm in C++

Started by
3 comments, last by Sneftel 16 years, 2 months ago
Does anyone happen to have a fast algorithm to generate a unique ID in C++? I would prefer something that could squeeze inside a long. The UID's don't have to be globally unique, just unique to the current install of my game. I figured I would want to use the current date in some way to derive a UID, I just wasn't really sure what to do beyond that.
Advertisement
If they don't need to outlive the application: pointer-to-int conversion should be fine.

If they don't need to outlive persistent storage (savegame): load ID's on start, remap them to current application's ID set, see previous solution.

What is the chance of collision? Are we talking 20 IDs per installation life-time, or 2^31 IDs per hour?

Will the IDs be shared between contexts? If so, can you segregate them (each application that's accessing shared ID namespace obtaines a marker (8 bits or so), and assigns IDs within remaining bits.

32 bits isn't really much for UIDs, unless you carefully manage them, and that involves knowledge of usage patterns.
Well, I am willing to expand to a 64 bit UID, I just didn't want to use a full 128-bit GUID. If I am going to do that, I might as well just use GUID's, as there are algorithms readily available to generate those.

There will be far more than 20 ID's, every object in the simulation will have an ID. That ID will be persisted, so it needs to be unique between application states, and between contexts, as objects may be saved in different data stores, but may need to reference UID's outside it's own context.
One common approach for IDs is to just keep a counter somewhere, and increment and return it each time you need a new ID. With persistence, this requires that you have a single location where the counter is persisted (and you are screwed if you lose that data, or try to use the other files on another machine with a lower persisted-counter).
As a rider to what Zahlman mentioned, one system for UIDs in distributed and/or multithreaded environments I've seen that works well is a per-thread pool drawing from a central pool. A thread will have a consecutive range of 65536 (or whatever) IDs which it will assign sequentially. Whenever it runs out, it increments a centralized counter by 65536 to continue. The advantage there is that you get thread safety with very little inter-thread communication; block allocations are uncommon enough that one can do them very quickly and simply using lock-free algorithms.

This topic is closed to new replies.

Advertisement