opnsense-src/lib/libc/gen/arc4random_uniform.c
Robert Clausecker 127709d30a lib/libc/gen: use Lemire's algorithm for arc4random_uniform().
Daniel Lemire has published a more efficient range reduction algorithm
for finding a random number in a given range without bias, reducing the
number of divisions to none in the common case and 1 in case the initial
sample is rejected.

This speeds up performance by 22% on amd64, 15% on i386, and 70% on armv7.

os: FreeBSD
arch: amd64
cpu: Intel(R) Core(TM) i7-4910MQ CPU @ 2.90GHz
                   │ benchmark.out │
                   │    sec/op     │
Arc4random_uniform     56.53n ± 0%
Fast_uniform           44.00n ± 0%
geomean                49.87n

Reviewed by:	cem
Approved by:	emaste
Differential Revision:	https://reviews.freebsd.org/D47659
2024-12-02 11:41:11 +01:00

47 lines
1 KiB
C

/*-
* SPDX-License-Identifier: 0BSD
*
* Copyright (c) Robert Clausecker <fuz@FreeBSD.org>
* Based on a publication by Daniel Lemire.
* Public domain where applicable.
*
* Daniel Lemire, "Fast Random Integer Generation in an Interval",
* Association for Computing Machinery, ACM Trans. Model. Comput. Simul.,
* no. 1, vol. 29, pp. 1--12, New York, NY, USA, January 2019.
*/
#include <stdint.h>
#include <stdlib.h>
uint32_t
arc4random_uniform(uint32_t upper_bound)
{
uint64_t product;
/*
* The paper uses these variable names:
*
* L -- log2(UINT32_MAX+1)
* s -- upper_bound
* x -- arc4random() return value
* m -- product
* l -- (uint32_t)product
* t -- threshold
*/
if (upper_bound <= 1)
return (0);
product = upper_bound * (uint64_t)arc4random();
if ((uint32_t)product < upper_bound) {
uint32_t threshold;
/* threshold = (2**32 - upper_bound) % upper_bound */
threshold = -upper_bound % upper_bound;
while ((uint32_t)product < threshold)
product = upper_bound * (uint64_t)arc4random();
}
return (product >> 32);
}