1
0
mirror of https://github.com/postgres/postgres.git synced 2025-12-21 05:21:08 +03:00

Replace random(), pg_erand48(), etc with a better PRNG API and algorithm.

Standardize on xoroshiro128** as our basic PRNG algorithm, eliminating
a bunch of platform dependencies as well as fundamentally-obsolete PRNG
code.  In addition, this API replacement will ease replacing the
algorithm again in future, should that become necessary.

xoroshiro128** is a few percent slower than the drand48 family,
but it can produce full-width 64-bit random values not only 48-bit,
and it should be much more trustworthy.  It's likely to be noticeably
faster than the platform's random(), depending on which platform you
are thinking about; and we can have non-global state vectors easily,
unlike with random().  It is not cryptographically strong, but neither
are the functions it replaces.

Fabien Coelho, reviewed by Dean Rasheed, Aleksander Alekseev, and myself

Discussion: https://postgr.es/m/alpine.DEB.2.22.394.2105241211230.165418@pseudo
This commit is contained in:
Tom Lane
2021-11-28 21:32:36 -05:00
parent f44ceb46ec
commit 3804539e48
50 changed files with 543 additions and 480 deletions

View File

@@ -13,15 +13,14 @@
#ifndef SAMPLING_H
#define SAMPLING_H
#include "common/pg_prng.h"
#include "storage/block.h" /* for typedef BlockNumber */
/* Random generator for sampling code */
typedef unsigned short SamplerRandomState[3];
extern void sampler_random_init_state(long seed,
SamplerRandomState randstate);
extern double sampler_random_fract(SamplerRandomState randstate);
extern void sampler_random_init_state(uint32 seed,
pg_prng_state *randstate);
extern double sampler_random_fract(pg_prng_state *randstate);
/* Block sampling methods */
@@ -32,13 +31,13 @@ typedef struct
int n; /* desired sample size */
BlockNumber t; /* current block number */
int m; /* blocks selected so far */
SamplerRandomState randstate; /* random generator state */
pg_prng_state randstate; /* random generator state */
} BlockSamplerData;
typedef BlockSamplerData *BlockSampler;
extern BlockNumber BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
int samplesize, long randseed);
int samplesize, uint32 randseed);
extern bool BlockSampler_HasMore(BlockSampler bs);
extern BlockNumber BlockSampler_Next(BlockSampler bs);
@@ -47,7 +46,7 @@ extern BlockNumber BlockSampler_Next(BlockSampler bs);
typedef struct
{
double W;
SamplerRandomState randstate; /* random generator state */
pg_prng_state randstate; /* random generator state */
} ReservoirStateData;
typedef ReservoirStateData *ReservoirState;