Python Random vs. Cython C Rand for Dice Rolls

Chris Angelico rosuav at gmail.com
Sun Jun 7 13:23:24 EDT 2015


On Mon, Jun 8, 2015 at 3:17 AM, C.D. Reimer <chris at cdreimer.com> wrote:
> This is the Python script that takes ~197 seconds to complete.
>
> import random, time
>
> startTime = time.time()
>
> f = [0] * 12
>
> for i in range(50000000):
>
>     a = random.randint(1,6)
>
>     b = random.randint(1,6)
>
>     f[(a + b) - 1] += 1
>
> print "\nTOTAL SPOTS","\tNUMBER OF TIMES\n"
>
> for i in range(1,12):
>
>     print ' ' + str(i + 1), '\t\t ', f[i]
>
> print '\n', time.time() - startTime

Before you go any further, can you just try this script, please, and
see how long it takes to run?

import random, time
startTime = time.time()
for i in range(50000000):
    pass
print '\n', time.time() - startTime

I know, seems a stupid thing to try, right? But you're using Python 2,
as evidenced by the print statements, and that means that range() is
constructing a 50M element list. It's entirely possible that that's a
significant part of your time - allocating all that memory, populating
it, and then disposing of it at the end (maybe).

Maybe it'll turn out not to be significant, but there's only one way
to find out.

ChrisA



More information about the Python-list mailing list