Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

djberg96 (2603)

  (email not shown publicly)

Journal of djberg96 (2603)

Tuesday January 07, 2003
09:20 AM

GLCS abandonment

[ #9810 ]
Many people are familiar with The Great Computer Language Shootout. I think it's a pretty cool site, despite whatever flaws it may have.

Last night someone popped into IRC wondering how Ruby's hash access compared to Perl's. According to the GLCS site (Hashes, Part I, not Part II), Perl is about twice as fast. This is the code:

n = (ARGV.shift || 1).to_i

hash = {}
for i in 1..n
    hash['%x' % i] = 1

c = 0
n.downto 1 do |i|
    c += 1 if hash.has_key? i.to_s

puts c

However, I decided to see if I could optimize the code a bit. Using some benchmarks and the profiler, I've discovered that "for" loops are faster than "downto", and "while" loops are faster than "for". The former is generally known, but the latter generally isn't. So, I rewrote it as this:

n = (ARGV.shift || 1).to_i

hash = {}
i = 0
while i < n
   hash['%x' %i] = 1
   i += 1

c = 0
while n >= 1
    c += 1 if hash.has_key? i.to_s
    n -= 1

puts c

Sending 10,000 as the number, I was able to drop the execution time from 9.5-10.5 seconds to 5-6 seconds (on my computer). At least, that's what the profiler told me.

I sent this code snippet to Doug Bagley, only to realize too late that he has abandoned the web site to work on other things. That's too bad, really. Maybe some other folks would like to pick it up? I'm hoping to at least bump up Ruby's rating over Python's, if not Perl's. :)

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.