From: Ara.T.Howard@... Date: 2004-01-13T02:11:40+09:00 Subject: Re: faster integer arithmetics & arbitrary precision floating number On Tue, 13 Jan 2004, David Garamond wrote: > Date: Tue, 13 Jan 2004 00:09:53 +0900 > From: David Garamond > Newsgroups: comp.lang.ruby > Subject: faster integer arithmetics & arbitrary precision floating number > > 1. Is there a way in Ruby to speed up 32bit integer arithmetics (only > involving numbers & sums up to 2^32-1)? I want to use Ruby for > summarizing network traffic logs, but it's pathetically slow compared to > Perl: > > $ time ruby -e'1000000.times{1073741823+1073741824}' > > real 0m23.693s > user 0m5.720s > sys 0m0.610s > $ time perl -e'for(1..1000000){1073741823+1073741824}' > > real 0m1.142s > user 0m0.320s > sys 0m0.050s > > since 2**30 is already in the Bignum range. if there is someway you can organized your problem into arrays (eg. collecting the item to sum into one), narray might be the way to go, it offer blindingly fast numerical operations: ~ > time ruby -r narray -e 'NArray.int(1000000)[true] = 1073741823+1073741824' real 0m0.025s user 0m0.010s sys 0m0.010s ~ > time perl -e'for(1..1000000){1073741823+1073741824}' real 0m0.128s user 0m0.130s sys 0m0.000s in fact, the operations are fast enough that you might simply be able to use normal ruby objects and ignore the Fixnum/Bignum distinction - which is a very useful (accurate) abstraction: ~ > irb -r narray irb(main):001:0> (na=NArray.object(1000000))[true] = 1073741823+1073741824 => 2147483647 irb(main):002:0> a=Time.now; p(na.sum); b=Time.now; b.to_f - a.to_f 2147483647000000 => 0.882834911346436 not bad for summing a million numbers with arbitrary precision eh? -a -- ATTN: please update your address books with address below! =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328 | STP :: http://www.ngdc.noaa.gov/stp/ | NGDC :: http://www.ngdc.noaa.gov/ | NESDIS :: http://www.nesdis.noaa.gov/ | NOAA :: http://www.noaa.gov/ | US DOC :: http://www.commerce.gov/ | | The difference between art and science is that science is what we | understand well enough to explain to a computer. | Art is everything else. | -- Donald Knuth, "Discover" | | /bin/sh -c 'for l in ruby perl;do $l -e "print \"\x3a\x2d\x29\x0a\"";done' ===============================================================================