|
| 1 | +======================== |
| 2 | +Python SonyFlake (Turbo) |
| 3 | +======================== |
| 4 | + |
| 5 | +A `SonyFlake <https://github.com/sony/sonyflake>`_ ID generator tailored for |
| 6 | +high-volume ID generation. |
| 7 | + |
| 8 | +Installation |
| 9 | +============ |
| 10 | + |
| 11 | +.. code-block:: sh |
| 12 | +
|
| 13 | + pip install sonyflake-turbo |
| 14 | +
|
| 15 | +Usage |
| 16 | +===== |
| 17 | + |
| 18 | +Easy mode: |
| 19 | + |
| 20 | +.. code-block:: python |
| 21 | +
|
| 22 | + from sonyflake_turbo import SonyFlake |
| 23 | +
|
| 24 | + sf = SonyFlake(0x1337, 0xCAFE) |
| 25 | +
|
| 26 | + for _, id_ in zip(range(10), sf): |
| 27 | + print(f"{id_:016x}") |
| 28 | +
|
| 29 | +Turbo mode: |
| 30 | + |
| 31 | +.. code-block:: python |
| 32 | +
|
| 33 | + from datetime import datetime, timezone |
| 34 | + from random import sample |
| 35 | + from timeit import timeit |
| 36 | +
|
| 37 | + from sonyflake_turbo import SONYFLAKE_MACHINE_ID_MAX, SonyFlake |
| 38 | +
|
| 39 | + epoch = datetime(2025, 6, 5, tzinfo=timezone.utc) |
| 40 | +
|
| 41 | + for count in [32, 16, 8, 4, 2, 1]: |
| 42 | + machine_ids = sample(range(SONYFLAKE_MACHINE_ID_MAX + 1), count) |
| 43 | + sf = SonyFlake(*machine_ids, start_time=int(epoch.timestamp())) |
| 44 | + t = timeit(lambda: [next(sf) for _ in range(1000)], number=1000) |
| 45 | + print(f"Speed: 1M ids / {t:.2f}sec with {count} machine IDs") |
| 46 | +
|
| 47 | +Important Notes |
| 48 | +=============== |
| 49 | + |
| 50 | +SonyFlake algorithm produces IDs at rate 256 IDs per 10msec per 1 Machine ID. |
| 51 | +One obvious way to increase the throughput is to use multiple generators with |
| 52 | +different Machine IDs. This library provides a way to do exactly that by |
| 53 | +passing multiple Machine IDs to the constructor of the `SonyFlake` class. |
| 54 | +Generated IDs are non-repeating and are always increasing. But be careful! You |
| 55 | +should be conscious about assigning Machine IDs to different processes and/or |
| 56 | +machines to avoid collisions. This library does not come with any Machine ID |
| 57 | +management features, so it's up to you to figure this out. |
| 58 | + |
| 59 | +This library has limited free-threaded mode support. It won't crash, but |
| 60 | +you won't get much performance gain from multithreaded usage. Consider |
| 61 | +creating generators per thread instead of sharing them across multiple |
| 62 | +threads. |
| 63 | + |
| 64 | +Development |
| 65 | +=========== |
| 66 | + |
| 67 | +Install: |
| 68 | + |
| 69 | +.. code-block:: sh |
| 70 | +
|
| 71 | + python3 -m venv env |
| 72 | + . env/bin/activate |
| 73 | + pip install -e .[test] |
| 74 | +
|
| 75 | +Run tests: |
| 76 | + |
| 77 | +.. code-block:: sh |
| 78 | +
|
| 79 | + py.test |
| 80 | +
|
| 81 | +Building wheels: |
| 82 | + |
| 83 | +.. code-block:: sh |
| 84 | +
|
| 85 | + pip install cibuildwheel |
| 86 | + cibuildwheel |
0 commit comments