From: Lou Vanek Date: 2006-01-06T11:34:34+09:00 Subject: Re: [SUMMARY] Numeric Maze (#60) Then I guess I just love implementation details. ;) >ruby -e "puts (2**29).class" Fixnum >time ruby -e '1_000_000.times { 2**29 }' real 0m25.788s user 0m25.686s sys 0m0.031s >time ruby -e '1_000_000.times { 2.0**29 }' real 0m1.233s user 0m1.234s sys 0m0.000s >ruby -e "puts (2.0**29).class" Float >time ruby -e '1_000_000.times { 1<<29 }' real 0m0.559s user 0m0.577s sys 0m0.000s >ruby -e "puts (1<<29).class" Fixnum >time ruby -e '1_000_000.times { 2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2 }' real 0m5.970s user 0m5.983s sys 0m0.015s >ruby -e "puts (2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2).class" Fixnum Simon Kr�ger wrote: > Lou Vanek wrote: > >> The shift operator comes in handy and can save a lot of time. >> These are equivalent operations: >> >> >time ruby -e '1_000_000.times { || 2**31 }' >> >> real 0m33.225s >> user 0m32.452s >> sys 0m0.015s >> >time ruby -e '1_000_000.times { || 1<<31 }' >> >> real 0m3.469s >> user 0m3.421s >> sys 0m0.000s >> >time ruby -e '1_000_000.times { || >> 2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2 }' >> >> real 0m13.839s >> user 0m13.656s >> sys 0m0.015s >> >> >> Kero wrote: > > > This is an implementation detail, > > the ** operator of Fixnum calls rb_big_pow converting self to a Bignum > regardless of the value. '<<' checks the size of the result and uses > real bitshifting if possible. > > While this was interresting to me it's not the explanation of the effect > above because the value 2**31 is always a bignum, but the implementation > of the ** operator in Bignum isn't very fast (while shifting the > internal representation of the bignum is faster) > > To prove my point that this isn't realy because bitshifts are faster try > this: > > 1_000_000.times { || 2.0**30 } > > At least on my machine this is faster than any of your three examples > above. (if you choose smaller values '<<' will be the fastest because it > doesn't convert to bignums as stated above) > > cheers > > Simon