Created
February 14, 2020 12:55
-
-
Save RazorSh4rk/b54cec99acea0a4b4ae05f428f3e33a4 to your computer and use it in GitHub Desktop.
scala speed test
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
import java.time.Instant | |
import java.time.Duration | |
import scala.util.Random | |
import scala.math.abs | |
import scala.math.pow | |
object Main extends App { | |
val LEN = 10_000 | |
val r = new Random() | |
val l = List.tabulate(LEN)(el => r.between(-5000, 5000)).sorted | |
println("starting method 1...") | |
val start1 = Instant.now | |
val sorted1 = _1(l) | |
val end1 = Instant.now | |
val time1 = Duration.between(start1, end1).toMillis | |
println("starting method 2...") | |
val start2 = Instant.now | |
val sorted2 = _2(l, List()) | |
val end2 = Instant.now | |
val time2 = Duration.between(start2, end2).toMillis | |
println("starting method 3...") | |
val start3 = Instant.now | |
val sorted3 = _3(l) | |
val end3 = Instant.now | |
val time3 = Duration.between(start3, end3).toMillis | |
println(s"method 1: $time1 ms, method 2: $time2 ms, method 3: $time3 ms") | |
def _1(l: List[Int]): List[Double] = { | |
l.map(el => pow(el, 2)).sorted | |
} | |
def _2(l: List[Int], accum: List[Double]): List[Double] = { | |
if(l.length == 0) accum | |
else { | |
val first = pow(l.head, 2) | |
val last = pow(l.last, 2) | |
if(first > last) | |
_2(l.tail, ( List(first):::accum )) | |
else | |
_2(l.dropRight(1), ( List(last):::accum )) | |
} | |
} | |
def _3(l: List[Int]): List[Double] = { | |
var ret = List.tabulate(LEN)(el => 0d) | |
var targetIndex = ret.length - 1 | |
var firstIndex = 0 | |
var lastIndex = ret.length - 1 | |
while(targetIndex != -1) { | |
if(l(firstIndex) > l(lastIndex)) { | |
ret = ret.updated(targetIndex, pow(l(firstIndex), 2)) | |
firstIndex += 1 | |
targetIndex -= 1 | |
} else { | |
ret = ret.updated(targetIndex, pow(l(lastIndex), 2)) | |
lastIndex -= 1 | |
targetIndex -= 1 | |
} | |
} | |
ret | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment