Dado elejemplo dado por profundidad, generar un programa que haga el producto vectorial de forma paralela.
\[
a = \{1,2,3\}, b = \{4,5,6\}, a.b = 1*4+2*5+3*6 = 32
\]
Solucion¶
Archivo Sumar.scala¶
package taller
import common._
class Sumar {
def sumSegment(a: Array[Int], b: Array[Int], i: Int, f: Int): Int = {
(i until f).map(x => a(x)*b(x)).sum
}
def suma(a: Array[Int], b:Array[Int], i: Int, f: Int, prof: Int, cnt:Int = 0): Int = {
if (cnt >= prof)
sumSegment(a, b, i, f)
else {
val m: Int = (i + f) / 2
val (s1, s2) = parallel (
suma(a, b, i, m, prof, cnt+1),
suma(a, b, m, f, prof, cnt+1)
)
s1 + s2
}
}
}
Archivo App.scala¶
/*
* This Scala source file was generated by the Gradle 'init' task.
*/
package taller
import org.scalameter._
object App {
def main(args: Array[String]): Unit = {
val objSumar = new Sumar()
val size = 1000000
val arrA = (1 to size).toArray
val arrB = (1 to size).map(x => x*2).toArray
val t1 = withWarmer(new Warmer.Default) measure {
objSumar.suma(arrA, arrB, 0, arrA.length, 0) //Secuencial
}
val t2 = withWarmer(new Warmer.Default) measure {
objSumar.suma(arrA, arrB, 0, arrA.length, 1) //Paralelo prof 1
}
val t3 = withWarmer(new Warmer.Default) measure {
objSumar.suma(arrA, arrB, 0, arrA.length, 2) //Paralelo prof 2
}
val t4 = withWarmer(new Warmer.Default) measure {
objSumar.suma(arrA, arrB, 0, arrA.length, 3) //Paralelo prof 3
}
val t5 = withWarmer(new Warmer.Default) measure {
objSumar.suma(arrA, arrB, 0, arrA.length, 4) //Paralelo prof 4
}
println(s"Tiempo Secuencial: $t1 ms")
println(s"Tiempo Paralelo prof 1 (2 hilos): $t2 ms")
println(s"Tiempo Paralelo prof 2 (4 hilos): $t3 ms")
println(s"Tiempo Paralelo prof 3 (8 hilos): $t4 ms")
println(s"Tiempo Paralelo prof 4 (16 hilos): $t5 ms")
}
def greeting(): String = "Hello, world!"
}
Ejecución¶
Tiempo Secuencial: 11.097029 ms ms
Tiempo Paralelo prof 1 (2 hilos): 6.365939 ms ms
Tiempo Paralelo prof 2 (4 hilos): 5.579212 ms ms
Tiempo Paralelo prof 3 (8 hilos): 5.548574 ms ms
Tiempo Paralelo prof 4 (16 hilos): 9.574517 ms ms