[BangPypers] python speed comparison

Abhishek Mishra ideamonk at gmail.com
Fri Aug 6 16:38:53 CEST 2010


>
> <snip>
>


> Your python code as is clocked about 72 seconds on my notebook. The
> following came in at about 4.6 seconds (just has a small trick of reusing
> earlier results)
>
> import time
> start =time.time()
> longest = None
> longest_elements = 0
> solved = {}
> for val in xrange(1,1000000) :
>    counter = 1
>    number = val
>    while number != 1 :
>        number = number / 2 if number % 2 == 0 else 3 * number + 1
>        if number in solved :
>            counter = counter + solved[number]
>            break
>        else :
>            counter = counter + 1
>    if counter > longest_elements :
>        longest_elements = counter
>        longest = val
>    solved[val] = counter
> end = time.time()
> print "Time:", end - start
> print longest, ':', longest_elements
>
> Dhananjay
>
>
If you are still looking forward to squeeze around 200ms more, try bit ops -
Original code by Dhananjay averages to 4.25823163986s on my machine

While if you change -
number = number / 2 if number % 2 == 0 else 3 * number + 1
into
number =  3*number+1 if number&1 else number >> 1

it averages 4.058642069496667s on my machine.

Abhishek


More information about the BangPypers mailing list