Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.olegchir.vectorperf
- import scala.collection.mutable.{ListBuffer, ArrayBuffer}
- object Main {
- private trait IVector2D {
- def add(v : IVector2D)
- def mult(t:Transform2D):IVector2D
- def xval: Double
- def yval: Double
- }
- private class MutableVector2D (var x: Double, var y: Double) extends IVector2D {
- def add(v : IVector2D) = {x = v.xval; y = v.yval}
- def mult(t:Transform2D):MutableVector2D = {x = x * t.cos - y * t.sin + t.tx; y = y * t.sin + y * t.cos + t.ty;this}
- def xval = x
- def yval = y
- override def toString = "MutableVector2D(" + "x=" + x + ", y=" + y + ')'
- }
- private class ImmutableVector2D (val x: Double, val y: Double) extends IVector2D {
- def add(v : IVector2D) = {new ImmutableVector2D(v.xval,v.yval)}
- def mult(t:Transform2D):IVector2D = {new ImmutableVector2D(x * t.cos - y * t.sin + t.tx, y * t.sin + y * t.cos + t.ty)}
- def xval = x
- def yval = y
- override def toString = "ImmutableVector2D(" + "x=" + x + ", y=" + y + ')'
- }
- private type Vector2D = ImmutableVector2D
- private class Transform2D (val angle: Double, val tx: Double, val ty: Double) {
- val cos: Double = Math.cos(angle)
- val sin: Double = Math.sin(angle)
- }
- private def calc(v: List[Vector2D], t: Transform2D): Vector2D = {
- val res = new Vector2D(0, 0)
- v.foreach((vec: Vector2D) => res.add(vec.mult(t)))
- res
- }
- implicit def intWithTimes(n: Int) = new {
- def times(f: => Unit) = 1 to n foreach {_ => f}
- }
- private def run(str: String, vects: List[Vector2D], transf: Transform2D): Unit = {
- println("Start of " + str)
- var vector: Vector2D = null
- val N = 1000
- val started = System.nanoTime()
- N times {
- vector = calc(vects, transf)
- }
- val totalTime = (System.nanoTime() - started) * 1e-9
- println("Res = " + vector)
- println("Total time = " + totalTime + " (sec)")
- println("Average time = " + totalTime / N + " (sec)")
- println("End of " + str)
- }
- def main(a: Array[String]) = {
- val size = 1000000
- val vectsBuffer: ListBuffer[Vector2D] = new ListBuffer[Vector2D]
- for (i <- 0 until size) {
- val d = (1.0 * i) / size
- vectsBuffer += new Vector2D(d, d)
- }
- val vects: List[Vector2D] = vectsBuffer.toList
- val transf = new Transform2D(1.0, -2.5, 5.0);
- run("Warm Up", vects, transf)
- println
- run("Actual", vects, transf)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement