Python Random vs. Cython C Rand for Dice Rolls

Chris Angelico rosuav at gmail.com
Sun Jun 7 14:12:58 EDT 2015


On Mon, Jun 8, 2015 at 3:59 AM, C.D. Reimer <chris at cdreimer.com> wrote:
> On 6/7/2015 10:23 AM, Chris Angelico wrote:
>>
>> 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).
>
>
> PS Z:\projects\programming\python\basic_games\fastdice> python
> test_random_time.py
>
> 4.84700012207
>
>
> So... I'm not looking at the problem on the Python side in the correct way?
>
> In particular, I'm using the wrong container type?

The only thing I was looking at here was range() vs xrange(). Try
using xrange here, and see how much faster your null loop is, and then
make the corresponding change to your real program and see if it's
equally faster. But since your main routine was taking ~200 seconds
and the null took ~5, it's not as big a deal as I thought; and a good
slab of that time will be spent on the null iteration, rather than the
list construction. (In fact, it's entirely possible you have a site.py
or something that goes "range = xrange".)

> I was thinking "array" (like the Cython version) when I put the Python
> script together. I got an error message at one point about indexing the
> "list" that threw me off for a while. Since it looks like an array, walks
> like an array, and quack likes array, I fixed the indexing problem like an
> array. A list != array? :)

The main difference between lists and arrays is that lists can grow
and shrink, which you're not using here. So I'd expect that, for the
purposes of this program, they're in the same space. You can use a
Python list the way you'd use a C array, generally. They can just do
ever so much more.

ChrisA



More information about the Python-list mailing list