PHpullh
학습 라이브러리/Kotlin/프로파일링 기법

KOTLIN · 성능

프로파일링 기법

코드의 성능 병목을 찾는 프로파일링 기법입니다. 시간 측정, 메모리 추적, 핫스팟 분석을 다룹니다.

성능고급profilinghotspotperformance-analysistiming

핵심 설명

코드의 성능 병목을 찾는 프로파일링 기법입니다. 시간 측정, 메모리 추적, 핫스팟 분석을 다룹니다.

Kotlin code

import kotlin.system.measureTimeMillis

class SimpleProfiler {
    private val timings = mutableMapOf<String, MutableList<Long>>()

    inline fun <T> profile(name: String, block: () -> T): T {
        val start = System.nanoTime()
        val result = block()
        val elapsed = System.nanoTime() - start
        timings.getOrPut(name) { mutableListOf() }.add(elapsed)
        return result
    }

    fun report() {
        println("=== 프로파일링 결과 ===")
        timings.entries.sortedByDescending { it.value.sum() }.forEach { (name, times) ->
            val total = times.sum() / 1_000_000.0
            val avg = total / times.size
            val max = times.max() / 1_000_000.0
            println("  $name: 총=${"%.2f".format(total)}ms, 평균=${"%.3f".format(avg)}ms, 최대=${"%.3f".format(max)}ms, 호출=${times.size}회")
        }
    }
}

fun main() {
    val profiler = SimpleProfiler()
    val data = (1..100_000).toList()

    repeat(5) {
        profiler.profile("filter+map") {
            data.filter { it % 3 == 0 }.map { it * 2 }
        }
        profiler.profile("sequence") {
            data.asSequence().filter { it % 3 == 0 }.map { it * 2 }.toList()
        }
        profiler.profile("manual loop") {
            buildList {
                for (i in data) if (i % 3 == 0) add(i * 2)
            }
        }
    }

    profiler.report()

    // JVM 메모리 상태
    val rt = Runtime.getRuntime()
    println("
메모리: 사용=${(rt.totalMemory() - rt.freeMemory()) / 1024 / 1024}MB, 최대=${rt.maxMemory() / 1024 / 1024}MB")
}

학습 팁

IntelliJ의 내장 프로파일러나 VisualVM을 사용하면 CPU/메모리 핫스팟을 시각적으로 분석할 수 있습니다.

주의할 점

프로덕션 코드에 프로파일링 코드를 남겨두면 성능에 영향을 줍니다. AOP나 디버그 빌드 전용으로 분리하세요.

자주 묻는 질문

프로파일링 기법란 무엇인가요?

코드의 성능 병목을 찾는 프로파일링 기법입니다. 시간 측정, 메모리 추적, 핫스팟 분석을 다룹니다.

프로파일링 기법 학습 시 주의할 점은 무엇인가요?

프로덕션 코드에 프로파일링 코드를 남겨두면 성능에 영향을 줍니다. AOP나 디버그 빌드 전용으로 분리하세요.

Continue Learning

Kotlin 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.