스칼라에서는 주어진 숫자에서 모든 숫자의 곱을 찾는 방법을 작성해야합니다. 다음 스 니펫이 있습니다.
def productDigits(number: Int): Int = {
def helper(current: Int, accumulator: Int): Int = {
current match {
case current if current < 10 => accumulator * current
case _ => helper(current / 10, accumulator * (current % 10))
}
}
helper(number, 1)
}
더 좋은 방법이 있습니까?
다음은 OP의 재귀 솔루션과 Luis의 한 줄짜리 jmh 벤치 마크입니다.
실행 중
sbt "jmh:run -i 10 -wi 10 -f 2 -t 1 bench.So59652263"
어디
@State(Scope.Benchmark)
@BenchmarkMode(Array(Mode.Throughput))
class So59652263 {
def _dexter2305(number: Int): Int = {
def helper(current: Int, accumulator: Int): Int = {
current match {
case current if current < 10 => accumulator * current
case _ => helper(current / 10, accumulator * (current % 10))
}
}
helper(number, 1)
}
def _luis(number: Int): Int = number.toString.map(_.asDigit).product
val num: Int = (math.random * 100000000).toInt
@Benchmark def dexter2305: Int = _dexter2305(num)
@Benchmark def luis: Int = _luis(num)
}
준다
[info] So59652263.dexter2305 thrpt 20 89093066.408 ± 1825286.801 ops/s
[info] So59652263.luis thrpt 20 11585098.230 ± 272966.526 ops/s
재귀 솔루션은 한 줄의 처리량보다 7 배 더 많은 처리량을 갖는 것으로 보입니다.
때 벤치마킹 number
입니다 String
대신Int
@State(Scope.Benchmark)
@BenchmarkMode(Array(Mode.Throughput))
class So59652263 {
def _dexter2305(number: String): Int = {
def helper(current: Int, accumulator: Int): Int = {
current match {
case current if current < 10 => accumulator * current
case _ => helper(current / 10, accumulator * (current % 10))
}
}
helper(number.toInt, 1)
}
def _luis(number: String): Int = number.map(_.asDigit).product
val num: String = (math.random * 100000000).toInt.toString
@Benchmark def dexter2305: Int = _dexter2305(num)
@Benchmark def luis: Int = _luis(num)
}
준다
[info] Benchmark Mode Cnt Score Error Units
[info] So59652263.dexter2305 thrpt 20 36237007.844 ± 1631349.975 ops/s
[info] So59652263.luis thrpt 20 13975984.042 ± 1890083.941 ops/s
우리는 재귀 솔루션을 볼 경우 여전히 때보 다 2.5의 작은 배 그러나 높은 처리량,이 number
되었다 Int
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다