Advertisement
Guest User

Untitled

a guest
Sep 13th, 2013
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.14 KB | None | 0 0
  1. package com.olegchir.vectorperf
  2.  
  3. import scala.collection.mutable.ArrayBuffer
  4.  
  5. object Main {
  6.   private class Vector2D (var x: Double, val y: Double) {
  7.  
  8.     def add(v : Vector2D) = {
  9.       new Vector2D(v.x,v.y)
  10.     }
  11.  
  12.     def mult(t:Transform2D):Vector2D = {
  13.       new Vector2D(x * t.cos - y * t.sin + t.tx, y * t.sin + y * t.cos + t.ty)
  14.     }
  15.  
  16.     override def toString = "Vector2D(" + "x=" + x + ", y=" + y + ')'
  17.   }
  18.  
  19.   private class Transform2D (val angle: Double, val tx: Double, val ty: Double) {
  20.     val cos: Double = Math.cos(angle)
  21.     val sin: Double = Math.sin(angle)
  22.   }
  23.  
  24.   private class VectorOfVector2D(private val size: Int) {
  25.     private val buffer = new ArrayBuffer[Double](2 * size)
  26.     def length() = size
  27.  
  28.     def get(idx: Int): Vector2D = new Vector2D(buffer.apply(idx * 2), buffer.apply(idx * 2 + 1))
  29.  
  30.     def add(v: Vector2D): Unit = {
  31.       buffer+=v.x
  32.       buffer+=v.y
  33.     }
  34.  
  35.     def set(idx: Int, v: Vector2D): Unit = {
  36.       buffer.update(2 * idx, v.x)
  37.       buffer.update(2 * idx + 1, v.y)
  38.     }
  39.   }
  40.  
  41.   private def calc(v: VectorOfVector2D, t: Transform2D): Vector2D = {
  42.     val res = new Vector2D(0, 0)
  43.     for (i <- 0 until v.length()) {
  44.       res.add(v.get(i).mult(t))
  45.     }
  46.     res
  47.   }
  48.  
  49.   private def run(str: String, vects: VectorOfVector2D, transf: Transform2D): Unit = {
  50.     println("Start of " + str)
  51.     var vector: Vector2D = null
  52.     val repeat = 1000
  53.     val started = System.nanoTime()
  54.     for (i <- 0 until repeat) {
  55.       vector = calc(vects, transf)
  56.     }
  57.     val totalTime = (System.nanoTime() - started) * 1e-9
  58.     println("Res = " + vector)
  59.     println("Total time = " + totalTime + " (sec)")
  60.     println("Average time = " + totalTime / repeat + " (sec)")
  61.     println("End of " + str)
  62.   }
  63.  
  64.  
  65.   def main(a: Array[String]) = {
  66.     val size = 1000000
  67.     val vects = new VectorOfVector2D(size)
  68.  
  69.     for (i <- 0 until size) {
  70.       val d = (1.0 * i) / size
  71.       //vects.set(i, new Vector2D(d, d))
  72.       vects.add(new Vector2D(d, d))
  73.     }
  74.  
  75.     val transf = new Transform2D(1.0, -2.5, 5.0);
  76.     run("Warm Up", vects, transf)
  77.     println
  78.     run("Actual", vects, transf)
  79.   }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement