www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/03/29/17:25:22

Date: Sun, 29 Mar 1998 14:23:42 -0800 (PST)
Message-Id: <199803292223.OAA18991@adit.ap.net>
Mime-Version: 1.0
To: ao950 AT FreeNet DOT Carleton DOT CA (Paul Derbyshire), djgpp AT delorie DOT com
From: Nate Eldredge <eldredge AT ap DOT net>
Subject: Re: Srandom()

At 07:44  3/29/1998 GMT, Paul Derbyshire wrote:
>
>
>
>How quickly does srandom() in DJGPP's libc execute? Would an added
>srandom() before every random() in a program that uses random()
>extensively cause a noticeable slowdown? Reason I ask is because something
>like that might be necessary to make a threadsafe random number generator
>class so that each random number generator instance can be seeded
>independently and give consistent results.

The canonical answer is "Profile it and see!", but anyway...

For `random', it depends on which RNG type you are using. There are ,
numbered 0 through 4. Type 0 is a simple linear congruential RNG, so it's
just an assignment. For the other types, it calls `random' a large number of
times (looks like 2^(n+2) for type n), presumably because the first few
values might not be so random.

`rand' is always a LCRNG, and hence `srand' and `rand' are very fast. Their
entire source is included for your viewing pleasure:
---
#include <stdlib.h>

static unsigned long long next = 0;

int
rand(void)
{
  next = next * 0x5deece66dLL + 11;
  return (int)((next >> 16) & RAND_MAX);
}

void
srand(unsigned seed)
{
  next = seed;
}
---
If you want to write a threadsafe RNG class, might it be better to steal the
sources for some RNG (or write your own) and work its structures and
routines into the class? It would certainly be faster.

Nate Eldredge
eldredge AT ap DOT net



- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019