From e1b63d7dec0e5d34940fe275a80c8d88b3e3247e Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Tue, 16 Nov 2021 03:20:07 -0800 Subject: [PATCH] Initialize mt19937 statically in function This reduces startup time --- native/jni/utils/misc.cpp | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/native/jni/utils/misc.cpp b/native/jni/utils/misc.cpp index 4911b2d74..505c44042 100644 --- a/native/jni/utils/misc.cpp +++ b/native/jni/utils/misc.cpp @@ -33,21 +33,17 @@ int fork_no_orphan() { return 0; } -constexpr char ALPHANUM[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; -static bool seeded = false; -static std::mt19937 gen; -static std::uniform_int_distribution dist(0, sizeof(ALPHANUM) - 2); int gen_rand_str(char *buf, int len, bool varlen) { - if (!seeded) { + constexpr char ALPHANUM[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + static std::mt19937 gen([]{ if (access("/dev/urandom", F_OK) != 0) mknod("/dev/urandom", 0600 | S_IFCHR, makedev(1, 9)); int fd = xopen("/dev/urandom", O_RDONLY | O_CLOEXEC); unsigned seed; xxread(fd, &seed, sizeof(seed)); - gen.seed(seed); - close(fd); - seeded = true; - } + return seed; + }()); + std::uniform_int_distribution dist(0, sizeof(ALPHANUM) - 2); if (varlen) { std::uniform_int_distribution len_dist(len / 2, len); len = len_dist(gen);