Last active
August 29, 2015 14:22
-
-
Save zhongwm/163b8670d8efb462c767 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.math.{MathContext, RoundingMode} | |
import scala.util.Random | |
/** | |
* <p></p> | |
* User: zwm<br/> | |
* Date: 6/5/15<br/> | |
* Time: 12:24 | |
*/ | |
object Racing extends App { | |
case class Hnm(hnmcode: String, bonus: Option[Double] = None) | |
private var _codes = Map[String, Hnm]() | |
def codes_=(value: Seq[Hnm]) = { | |
val mc: MathContext = new MathContext(2, RoundingMode.HALF_EVEN) | |
val totalMoney: BigDecimal = 100000.0 | |
val pieces: BigDecimal = 10000.0 | |
val average: BigDecimal = totalMoney / pieces | |
val vibration: BigDecimal = 4.5 | |
val dime: Double = 10000.0 / value.size | |
var currentSum = BigDecimal(0.0) | |
// Seq version: | |
System.gc() | |
val start1 = System.currentTimeMillis() | |
_codes = value.map { x: Hnm => | |
val bonus = { | |
if (Random.nextDouble() <= dime && currentSum + average + vibration < totalMoney) { | |
val current: BigDecimal = (average + (BigDecimal(Random.nextDouble() * 2 - 1) * vibration)).round(mc) | |
currentSum = currentSum + current | |
current.toDouble | |
} else 0.0 | |
} | |
x.hnmcode -> x.copy(bonus = Some(bonus)) | |
}.toMap | |
_codes = null | |
println("seq way time elapse(ms): " + (System.currentTimeMillis() - start1)) | |
// Par version: | |
println("----------------") | |
System.gc() | |
val start2 = System.currentTimeMillis() | |
val folded: (BigDecimal, Map[String, Hnm]) = value.par.foldLeft((currentSum, Map[String, Hnm]())) { case ((s, z), h) => | |
val bonus = | |
if (Random.nextDouble() <= dime && s + average + vibration < totalMoney) { | |
val current: BigDecimal = (average + (BigDecimal(Random.nextDouble() * 2 - 1) * vibration)).round(mc) | |
currentSum = currentSum + current | |
current.toDouble | |
} else 0.0 | |
(s + bonus, z + (h.hnmcode -> h.copy(bonus = Some(bonus)))) | |
} | |
_codes = folded._2 | |
println(s"par way time elapse(ms): ${System.currentTimeMillis() - start2}") | |
println("-----------------") | |
println(s"currentSum: $currentSum") | |
} | |
val hnms: Seq[Hnm] = 0 until 1500000 map { x: Int => Hnm(x.toString) } | |
codes_=(hnms) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment