From 6b863465b3e70ff52a657784618fe8122dcc8c7e Mon Sep 17 00:00:00 2001 From: Calcitem Date: Tue, 26 Dec 2023 01:15:28 +0800 Subject: [PATCH] perfect: Optimize random number generation by using static variables Modified the `chooseRandom` function to declare `std::random_device` and `std::mt19937` as static variables. This change ensures that these objects are initialized only once, reducing the overhead of repeatedly creating them on each function call. This optimization is expected to improve performance by approximately 0.02%. This aligns with practices in ggevay's original Visual Basic code, where the random generator was a static (Shared) variable. Reference: https://github.com/ggevay/malom/pull/3#discussion_r1349749827 Change-Id: Ic3b461caf52f533d4bbd5dc29ada65172d5c4450 --- src/perfect/perfect_player.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/perfect/perfect_player.cpp b/src/perfect/perfect_player.cpp index f6f525121..442d65465 100644 --- a/src/perfect/perfect_player.cpp +++ b/src/perfect/perfect_player.cpp @@ -444,9 +444,10 @@ int PerfectPlayer::NGMAfterMove(const GameState &s, AdvancedMove &m) template T PerfectPlayer::chooseRandom(const std::vector &l) { + static std::random_device rd; + static std::mt19937 gen(rd()); + if (gameOptions.getShufflingEnabled()) { - std::random_device rd; - std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, static_cast(l.size() - 1)); return l[dis(gen)]; }