Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Ichoran
Created June 12, 2018 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ichoran/4ba6460aadd93d7bd109bb712f75007f to your computer and use it in GitHub Desktop.
Save Ichoran/4ba6460aadd93d7bd109bb712f75007f to your computer and use it in GitHub Desktop.
Thyme benchmark of tap and pipe vs manual inlining
package bench
import scala.language.implicitConversions
import ichi.bench._
object Implicits {
final class ChainingOps[A](private val self: A) extends AnyVal {
@inline def tap[U](f: A => U): A = { f(self); self }
@inline def pipe[B](f: A => B): B = f(self)
}
implicit def implicitChains[A](a: A) = new ChainingOps(a)
}
class Bench {
import Implicits._
def run() {
val th = Thyme.warmed(0.03)
val a = Array.fill(1000)(Array.fill(10)(scala.util.Random.nextInt(3)))
def zlen(xs: Array[Int]): Int = {
var i = 0
while (i < xs.length) {
if (xs(i) == 0) return i
i += 1
}
i
}
def zlenTap(xs: Array[Int]): Int = {
var i = 0
while (i < xs.length) {
xs(i).tap(x => if (x == 0) return i)
i += 1
}
i
}
def zsum(xs: Array[Int]) = {
var s, i = 0
while (i < xs.length) {
val x = xs(i)
s += x*x + x + 2
i += 1
}
i
}
def zsumPipe(xs: Array[Int]) = {
var s, i = 0
while (i < xs.length) {
s += xs(i).pipe(x => x*x + x + 2)
i += 1
}
i
}
th.pbenchOff("len tap"){ var i, s = 0; while (i < a.length) { s += zlen(a(i)); i += 1 }; s }{ var i, s = 0; while (i < a.length) { s += zlenTap(a(i)); i += 1 }; s }
println
th.pbenchOff("sum pipe"){ var i, s = 0; while (i < a.length) { s += zsum(a(i)); i += 1 }; s }{ var i, s = 0; while (i < a.length) { s += zsumPipe(a(i)); i += 1 }; s }
println
println
}
}
object Bench {
def main(args: Array[String]) {
val b = new Bench()
for (i <- 1 to 5) b.run()
}
}
resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"
lazy val root = (project in file(".")).
settings(
name := "testing",
version := "0.0.0",
scalaVersion := "2.12.4",
scalacOptions ++= Seq(
"-unchecked", "-feature", "-deprecation", "-opt:l:method", "-opt:l:inline"
),
libraryDependencies += "com.github.ichoran" %% "thyme" % "0.1.2-SNAPSHOT"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment