Skip to content

Instantly share code, notes, and snippets.

@codeck
Created January 17, 2014 09:06
Show Gist options
  • Select an option

  • Save codeck/8470396 to your computer and use it in GitHub Desktop.

Select an option

Save codeck/8470396 to your computer and use it in GitHub Desktop.
def timeit[T](f:()=>T)(count:Int=1) = {
val st = System.nanoTime()
var ti = 0
var accu = collection.mutable.ListBuffer.empty[T]
while (ti < count) {
f() +=: accu
ti=ti+1
}
val ed = System.nanoTime()
println(s"${(ed-st)/1000000} ms")
accu.iterator
}
val array = Array.range(0, 1000000)
timeit(()=>{
var idx = 0
var sum = 0L
while(idx < array.length) {
sum = sum+array(idx)
idx = idx+1
}
sum
})(10).foreach(println)
case class MyInt(va:Int,sum:Long)
def Called(inc:MyInt) = inc.copy(sum = (inc.sum+inc.va))
def Caller(v:(MyInt)=>MyInt, a:Long, b:Int) = v(MyInt(b, a))
timeit(()=>{
var idx = 0
var sum = 0L
while(idx < array.length) {
sum = Caller(Called, sum, array(idx)).sum
idx = idx+1
}
sum
})(10).foreach(println)
timeit(()=>{
var idx = 0
var sum = 0L
while(idx < array.length) {
sum = ((a:Long, b: Int) => {
a+b
})(sum, array(idx))
idx = idx+1
}
sum
})(10).foreach(println)
timeit(()=>{
var idx = 0
var sum = 0L
while(idx < array.length) {
sum = ((a:Long, b: Int, c: Int) => {
a+b
})(sum, array(idx), 0)
idx = idx+1
}
sum
})(10).foreach(println)
timeit(()=>{
var idx = 0
var sum = 0L
while(idx < array.length) {
sum = ((a:Long, b:MyInt) => {
a+b.sum
})(array(idx), MyInt(0,sum))
idx = idx+1
}
sum
})(10).foreach(println)
@codeck
Copy link
Copy Markdown
Author

codeck commented Jan 17, 2014

1,2,3是快的,分别是裸跑,两个裸参数,完全case class的版本。4,5是慢的,是三个裸参数和一裸一不裸的版本。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment