Skip to content

Dice: replace std::mt19937 with a small generator - #2487

Open
DustinHab wants to merge 1 commit into
InfiniTimeOrg:mainfrom
DustinHab:dice-smaller-rng
Open

DustinHab wants to merge 1 commit into
InfiniTimeOrg:mainfrom
DustinHab:dice-smaller-rng

Conversation

@DustinHab

Copy link
Copy Markdown

Dice keeps a std::mt19937 as a member. That is 624 words of state, and seeding it from a std::seed_seq in the constructor needs a 2504 byte stack frame, measured with -fstack-usage. The constructor runs on the display task, which is created with 800 words, so 3200 bytes for the whole call chain. It fits, but not by much.

A dice roll does not need a Mersenne twister. This swaps it for xorshift32, which holds four bytes of state.

What it buys:

before after
constructor stack frame 2504 B 88 B
generator state 2496 B 4 B
build size 832 B smaller

std::uniform_int_distribution still does the range mapping, so the roll logic is unchanged.

Checked on the host, since a broken generator still compiles: 600000 d6 rolls stay within 0.7 % of even, a d99 reaches both 1 and 99, two different seeds give different sequences, a zero seed does not lock the generator into its fixed point, and the sequence does not repeat within two million values. Rolling in the simulator gives varying results and colours.

Paddle and Twos already use plain rand(), so Dice was the only screen carrying a heavyweight generator.

Dice keeps a std::mt19937 as a member, 624 words of state, and seeds it from
a std::seed_seq in the constructor. That seeding call alone needs a 2504 byte
stack frame, and the constructor runs on the display task, which has 3200
bytes in total.

A dice roll does not need a Mersenne twister. xorshift32 holds four bytes of
state, the constructor frame drops from 2504 to 88 bytes, and the build comes
out 832 bytes smaller.

Checked on the host: 600000 d6 rolls stay within 0.7 % of even, a d99 reaches
both 1 and 99, different seeds give different sequences, a zero seed does not
lock the generator, and the sequence does not repeat within two million
values. Rolling in the simulator gives varying results.
@github-actions

Copy link
Copy Markdown

Build size and comparison to main:

Section Size Difference
text 387072B -912B
data 936B 0B
bss 22936B 0B

Run in InfiniEmu

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant