Last active
July 4, 2021 15:18
-
-
Save shikajiro/4b4dc5f6c053130c649ab885a42086b5 to your computer and use it in GitHub Desktop.
処理の実行時間を計測してログに出力する便利ロジック
This file contains 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
/** | |
* 処理の実行時間を計測してログに出力する便利ロジック | |
* buildConfigFieldのPERFORMANCEフラグがtrueのとき、かつ、デバッグ時のみ計測される | |
呼び出しサンプル: | |
``` | |
val result: String | |
measure("copy time") { | |
// 計測したい処理 | |
result = execute() | |
} | |
``` | |
ログ出力サンプル | |
``` | |
D/Performance: 27,455,940 copy time | |
``` | |
*/ | |
@OptIn(ExperimentalContracts::class) | |
inline fun measure(msg: String, block: () -> Unit) { | |
// contractを設定することで、block内でval変数への代入が可能になる | |
contract { | |
callsInPlace(block, InvocationKind.EXACTLY_ONCE) | |
} | |
//PERFORMANCEとDEBUGを有効にしている場合のみ計測する | |
if (BuildConfig.PERFORMANCE && BuildConfig.DEBUG) { | |
val time = measureNanoTime { | |
block() | |
} | |
Log.d("Performance", "%,13dns $msg".format(time)) | |
} else { | |
// 計測しない場合は処理をそのまま実行する | |
block() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment