Skip to content

Instantly share code, notes, and snippets.

@shikajiro
Last active July 4, 2021 15:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shikajiro/4b4dc5f6c053130c649ab885a42086b5 to your computer and use it in GitHub Desktop.
Save shikajiro/4b4dc5f6c053130c649ab885a42086b5 to your computer and use it in GitHub Desktop.
処理の実行時間を計測してログに出力する便利ロジック
/**
* 処理の実行時間を計測してログに出力する便利ロジック
* 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