Skip to content

Instantly share code, notes, and snippets.

@windymelt
Created April 2, 2024 13:51
Show Gist options
  • Save windymelt/f59d212a90ba1c5b3a558ddf2c774b24 to your computer and use it in GitHub Desktop.
Save windymelt/f59d212a90ba1c5b3a558ddf2c774b24 to your computer and use it in GitHub Desktop.
Vector APIを使った
//> using scala 3.4.0
//> using dep "com.outr::scribe::3.13.2"
// run via:
// scala-cli -J --add-modules -J jdk.incubator.vector -J -Xmx16G vector.scala.sc
import jdk.incubator.vector.*
import scribe._
def mult2a(arr: Array[Double]): Array[Double] = arr.map(_ * 1.618)
inline def mult2v(
SP: VectorSpecies[java.lang.Double],
arr: Array[Double],
): Array[Double] = {
val buf = new Array[Double](arr.size)
var idx = 0
val spLength = SP.length()
while (idx < SP.loopBound(arr.size)) {
val mask = SP.indexInRange(idx, arr.size)
val vec = DoubleVector.fromArray(SP, arr, idx, mask)
val result = vec.mul(1.618)
result.intoArray(buf, idx, mask)
idx = idx + spLength
}
// handle the remaining elements
(idx to arr.size - 1) foreach { i =>
buf(i) = arr(i) * 1.618
}
buf
}
scribe.info("building array")
val hugeArray: Array[Double] =
(0 to 1_000_000).toArray.map(_.toDouble)
scribe.info("done")
scribe.info("mult2a")
val v1 = scribe.elapsed {
val result = mult2a(hugeArray)
scribe.info("done")
result
}
scribe.info(v1.take(10).mkString(", "))
scribe.info("mult2v")
inline def SP = DoubleVector.SPECIES_PREFERRED
val v2 = scribe.elapsed {
val result = mult2v(SP, hugeArray)
scribe.info("done")
result
}
scribe.info(v2.take(10).mkString(", "))
scribe.info("checking")
val asserted = assert(v1.sameElements(v2))
// ---
scribe.info("repeating mult2a")
val repeatedV1 = scribe.elapsed {
(0 to 10000).foreach { _ =>
mult2a(hugeArray)
}
scribe.info("done")
}
scribe.info("repeating mult2v")
val repeatedV2 = scribe.elapsed {
(0 to 10000).foreach { _ =>
mult2v(SP, hugeArray)
}
scribe.info("done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment