Skip to content

Commit

Permalink
tiny speedup to DenseVector#foreach
Browse files Browse the repository at this point in the history
  • Loading branch information
dlwh committed Jul 31, 2015
1 parent e25db29 commit 5fccba1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
15 changes: 15 additions & 0 deletions benchmark/src/main/scala/breeze/linalg/DenseVectorBenchmark.scala
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,21 @@ class DenseVectorBenchmark extends BreezeBenchmark with BuildsRandomVectors {
DenseVector.fill[Double](1024, 23)
}

def timeForeach(reps: Int) = runWith(reps, randomArray(4000)) { arr =>
var sum = 0.0
arr.foreach(sum += _)
sum
}

def timeLoop(reps: Int) = runWith(reps, randomArray(4000)) { arr =>
var sum = 0.0
val d = arr.data
cforRange(0 until arr.length) { i =>
sum += d(i)
}
sum
}

def valueAtBench(reps: Int, size: Int, stride: Int) = runWith(reps, {randomArray(size, stride=stride)})(arr => {
var i=0
var t: Double = 0
Expand Down
16 changes: 10 additions & 6 deletions math/src/main/scala/breeze/linalg/DenseVector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,16 @@ class DenseVector[@spec(Double, Int, Float, Long) V](val data: Array[V],
* @tparam U
*/
override def foreach[@spec(Unit) U](fn: (V) => U): Unit = {
var i = offset
var j = 0
while(j < length) {
fn(data(i))
i += stride
j += 1
if (stride == 1) { // ABCE stuff
cforRange(offset until (offset + length)) { j =>
fn(data(j))
}
} else {
var i = offset
cforRange(0 until length) { j =>
fn(data(i))
i += stride
}
}
}

Expand Down

0 comments on commit 5fccba1

Please sign in to comment.