Re: Premature Optimization

From: Gavin K.

However, I believe that’s a pure-ruby implementation of matrices and
vectors. A quick bit of Googling looks ike RNum[1] might be crazy fast
and do what you need. I’ve never used it. I’ve also never used
NArray[2], but it might do what you need.

So, I got NArray working on Windows with the One-Click Installer, and
yes, it’s just a bit faster than the pure-ruby
Matrix:

require ‘narray’
require ‘matrix’
require ‘benchmark’

ITERATIONS = 4
NUM_VECTORS = 100
VECTOR_SIZE = 5000

Benchmark.bmbm{ |x|
x.report( ‘Create Matrix’ ){
ITERATIONS.times{
@all = (1…NUM_VECTORS).map{
Vector[ *(1…VECTOR_SIZE).map{ rand.round } ]
}
}
}
ITERATIONS.times{
@all.inject{ |v1,v2| v1 + v2 }
}
}

x.report( ‘Create NArray’ ){
ITERATIONS.times{
@all = (1…NUM_VECTORS).map{
NVector[ *(1…VECTOR_SIZE).map{ rand.round } ]
}
}
}
ITERATIONS.times{
@all.inject{ |v1,v2| v1 + v2 }
}
}
}

Rehearsal -------------------------------------------------
Create Matrix 4.703000 0.016000 4.719000 ( 4.719000)
Add up Matrix 8.297000 0.016000 8.313000 ( 8.312000)
Create NArray 4.016000 0.000000 4.016000 ( 4.032000)
Add up NArray 0.031000 0.000000 0.031000 ( 0.031000)
--------------------------------------- total: 17.079000sec

``````                user     system      total        real
``````

Create Matrix 3.703000 0.000000 3.703000 ( 3.704000)
Add up Matrix 8.250000 0.000000 8.250000 ( 8.250000)
Create NArray 4.156000 0.000000 4.156000 ( 4.156000)
Add up NArray 0.032000 0.000000 0.032000 ( 0.031000)