generators : random shootout
Mark McEahern
marklists at mceahern.com
Fri Jan 11 17:46:30 EST 2002
Tim Peters:
> Heh. If you don't post gen.py and gen2.py, you realize nobody
> else has any idea what you're measuring -- right? Or how you're
> measuring it. From the output, looks like you're using
> time.clock() on a Linux box, but this kind of forced telepathy
> wears thin fast <wink>.
Silly me.
Here's gen.py:
#! /usr/bin/env python
# gen.py
# based on: http://www.bagley.org/~doug/shootout/
import sys
IM = 139968
IA = 3877
IC = 29573
LAST = 42
def gen_random(max):
global LAST
LAST = (LAST * IA + IC) % IM
return( (max * LAST) / IM )
def main():
try:
N = int(sys.argv[1])
except IndexError:
N = 1000
if N < 1:
N = 1
gr = gen_random
for i in xrange(1,N):
gr(100.0)
print "%.9f" % gr(100.0)
import time
timeIn = time.time()
main()
timeOut = time.time()
print "%f seconds." % (timeOut - timeIn)
Here's gen2.py:
#! /usr/bin/env python
# gen2.py
# based on: http://www.bagley.org/~doug/shootout/
from __future__ import generators
import sys
IM = 139968 # modulo
IA = 3877 # multiplier
IC = 29573 # increment
def gen_random(max):
last = 42 # initialize
while 1: # this generator can be called
indefinitely
last = (last * IA + IC) % IM # update prior value
rand = max * last / IM # generate the random number
yield rand # yield it
def main():
try:
N = int(sys.argv[1])
except IndexError:
N = 1000
if N < 1:
N = 1
gr = gen_random(100.0)
for i in xrange(1, N):
gr.next()
print "%.9f" % gr.next()
import time
timeIn = time.time()
main()
timeOut = time.time()
print "%f seconds." % (timeOut - timeIn)
Cheers,
// mark
More information about the Python-list
mailing list