반응형

보통 코드의 실행시간을 측정하기 위해서는.

val start = System.currentTimeMillis()
val result = inputPlus(1, 2)
val measuredTime = System.currentTimeMillis() - start
println("result => $result || measured time ==>$measuredTime")

 

이런식으로 실행시간을 측정하고 싶은 메소드의 시작과, 끝! 그에 대한 시간을 넣고 구할것 같습니다.

 

java로 Android 개발했을 대에는 Jake Wharton의 Hugo를 사용해서 실행시간을 logcat에 출력해서 사용하고 했지만,

https://github.com/JakeWharton/hugo

 

JakeWharton/hugo

Annotation-triggered method call logging for your debug builds. - JakeWharton/hugo

github.com

kotlin으로 넘어오면서, hugo를 사용하지 못하다 보니...

 

그래도 kotlin에는 사용하기 편한게 있습니다.

/**
 * Executes the given function [block] and returns an instance of [TimedValue] class, containing both
 * the result of the function execution and the duration of elapsed time interval.
 *
 * The elapsed time is measured with [TimeSource.Monotonic].
 */
@SinceKotlin("1.3")
@ExperimentalTime
public inline fun <T> measureTimedValue(block: () -> T): TimedValue<T> {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }

    return TimeSource.Monotonic.measureTimedValue(block)
}

/**
 * Executes the given [block] and returns an instance of [TimedValue] class, containing both
 * the result of function execution and the duration of elapsed time interval.
 *
 * The elapsed time is measured with the specified `this` [TimeSource] instance.
 */
@SinceKotlin("1.3")
@ExperimentalTime
public inline fun <T> TimeSource.measureTimedValue(block: () -> T): TimedValue<T> {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }

    val mark = markNow()
    val result = block()
    return TimedValue(result, mark.elapsedNow())
}

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.time/measure-timed-value.html

 

measureTimedValue - Kotlin Programming Language

 

kotlinlang.org

measureTimeValue를 이용하면 됩니다.

 kotlin 1.3 에 생겼고, 

 

val measuredTime = measureTimedValue {
            inputPlus(2, 3)
        }

println("result => ${measuredTime.value} || measured time ==>${measuredTime.duration}")

와 같이 사용하면, 간단히 사용할 수 있고, 해당 method의 결과도 확인할 수 있습니다.

반응형
반응형

Collection과 Sequence는 둘다 lambda의 확장함수( map, filter, find... )를 사용하여 원하는 결과를 찾아나갈 수 있습니다.

그런데 Collection의 확장함수를 사용하면, inline function을 통해서 매번 결과가 새롭게 만들어 집니다.

public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
    return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}

하지만 Sequence는 inline function이 아닌 chain call 을 통해서 결과를 이어 나갈 수 있습니다.

public fun <T, R> Sequence<T>.map(transform: (T) -> R): Sequence<R> {
    return TransformingSequence(this, transform)
}

 

같은 결과이지만, 중간 과정에서 결과를 보면,

val items = mutableListOf(1, 2, 3, 4, 5)
val result = items.map {
    it * it
}.filter {
    it % 2 == 0
}

map에서 새로운 1,4,9,16,25 가 만들어진 뒤, filter에서 새로운 4, 16의 결과만 만들지게 됩니다.

 

하지만 sequence는,

val items = mutableListOf(1, 2, 3, 4, 5)
val result = items.asSequence().map {
    it * it
}.filter {
    it % 2 == 0
}.toList()

1,1,2,4,3,9,4,16,5,25 의 순서로, 새로운 결과를 만들어지는게 아니라, 하나씩 확인을 해갑니다.

 

 

Collection에서 새로운 결과를 계속 만들다 보면 memory사용도 많아지게 되지만, Sequence로 하게 되면, 메모리 문제는 Collection보다는 덜 하게 됩니다.

반응형

+ Recent posts