The Computer Language
Benchmarks Game

spectral-norm Scala #5 program

source code

/* The Computer Language Benchmarks Game
   http://benchmarksgame.alioth.debian.org/
   contributed by Isaac Gouy
   parallel by the Anh Team
   Scala Futures version by Robert Wilton
*/
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global

object spectralnorm extends App {
  val n = if (args.length > 0) args(0).toInt else 100
  val u, v, tmp = Array.fill(n)(1.0)
  
  // Ordinary and transposed versions of infinite matrix
  val A = (i: Int, j: Int) => 1.0/((i + j) * (i + j + 1) / 2 + i + 1)
  val multiplyAv = multiply(A) _
  val At = (j: Int, i: Int) => 1.0/((i + j) * (i + j + 1) / 2 + i + 1)
  val multiplyAtv = multiply(At) _
  
  // Calculate the chunks and perform calculation.
  val threads = Runtime.getRuntime.availableProcessors
  val chunkSize = 1 + n/threads
  def chunkStart(t: Int) = t * chunkSize
  def chunkEnd(t: Int) = ((t + 1) * chunkSize) min n
  val chunks = (0 until threads) map { t => (chunkStart(t), chunkEnd(t)) }
  printf("%.09f\n",  work(chunks))
  
  // Matrix multiplication for a given range: w <- M*v
  def multiply(M: (Int,Int) => Double)
              (v: Array[Double], w: Array[Double])(start: Int, end: Int) {
    var i = start
    while (i < end) {
     var s = 0.0
     var j = 0
     while (j < n) { s += M(i,j)*v(j); j += 1 }
     w(i) =  s
     i += 1
    }
  }
  
  def work(chunks: Seq[(Int, Int)]) = {
    def split(f: (Int, Int) => Unit) = {
      val res = Future.sequence(
        chunks map { case (start, end) => Future { f(start, end) } } 
      )
      Await.result(res, 1.minute)
    }
    
    for (_ <- 1 to 10) {
      // Multiply by matrix & transpose
      split(multiplyAv(u, tmp))
      split(multiplyAtv(tmp, v))
      split(multiplyAv(v, tmp))
      split(multiplyAtv(tmp, u))
    }

    var vbv,vv = 0.0
    var i = 0
    while (i < n) {
      vbv += u(i)*v(i)
      vv += v(i)*v(i)
      i += 1
    }
    math.sqrt(vbv/vv)
  }
}
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
Scala compiler version 2.12.1 -- Copyright 2002-2016, LAMP/EPFL and Lightbend, Inc.
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)


Mon, 06 Feb 2017 05:56:31 GMT

MAKE:
mv spectralnorm.scala-5.scala spectralnorm.scala
/usr/local/src/scala-2.12.1/bin/scalac -optimise -target:jvm-1.8 spectralnorm.scala
warning: there was one deprecation warning; re-run with -deprecation for details
one warning found
7.01s to complete and log all make actions

COMMAND LINE:
 /usr/local/src/jdk1.8.0_121/bin/java  -Xbootclasspath/a:/usr/local/src/scala-2.12.1/lib/scala-library.jar:/usr/local/src/scala-2.12.1/lib/scala-actors-2.11.0.jar:/usr/local/src/scala-2.12.1/lib/akka-actor_2.11-2.3.4.jar:/usr/local/src/scala-2.12.1/lib/config-1.2.1.jar spectralnorm 5500

PROGRAM OUTPUT:
1.274224153