Created
June 12, 2018 22:06
-
-
Save Ichoran/4ba6460aadd93d7bd109bb712f75007f to your computer and use it in GitHub Desktop.
Thyme benchmark of tap and pipe vs manual inlining
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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