# MemoryUsageMetric

Artifact: [androidx.benchmark:benchmark-macro](https://developer.android.com/jetpack/androidx/releases/benchmark) [View Source](https://cs.android.com/search?q=file:androidx/benchmark/macro/Metric.kt+class:androidx.benchmark.macro.MemoryUsageMetric) Added in [1.2.0](https://developer.android.com/jetpack/androidx/releases/benchmark#1.2.0)

*** ** * ** ***


```
@ExperimentalMetricApi
class MemoryUsageMetric : TraceMetric
```

<br />

|---|---|---|---|
| [kotlin.Any](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-any/index.html) ||||
| ↳ | [androidx.benchmark.macro.Metric](https://developer.android.com/reference/kotlin/androidx/benchmark/macro/Metric) |||
|   | ↳ | [androidx.benchmark.macro.TraceMetric](https://developer.android.com/reference/kotlin/androidx/benchmark/macro/TraceMetric) ||
|   |   | ↳ | [androidx.benchmark.macro.MemoryUsageMetric](https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric) |

*** ** * ** ***

Metric for tracking the memory usage of the target application.

## Summary

| ### Nested types |
|---|
| `enum https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric.Mode : https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-enum/index.html<https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric.Mode>` |
| `enum https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric.SubMetric : https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-enum/index.html<https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric.SubMetric>` |

| ### Public constructors |
|---|
| `https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric#MemoryUsageMetric(androidx.benchmark.macro.MemoryUsageMetric.Mode,kotlin.collections.List,kotlin.String,kotlin.String)( mode: https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric.Mode, subMetrics: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/-list/index.html<https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric.SubMetric>, processNameSuffix: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/index.html, metricNameSuffix: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/index.html )` |

| ### Public functions |
|---|---|
| `open https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/-list/index.html<https://developer.android.com/reference/kotlin/androidx/benchmark/macro/Metric.Measurement>` | `https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric#getMeasurements(androidx.benchmark.macro.Metric.CaptureInfo,androidx.benchmark.traceprocessor.TraceProcessor.Session)( captureInfo: https://developer.android.com/reference/kotlin/androidx/benchmark/macro/Metric.CaptureInfo, traceSession: https://developer.android.com/reference/kotlin/androidx/benchmark/traceprocessor/TraceProcessor.Session )` Get the metric result for a given iteration given information about the target process and a TraceProcessor session |

## Public constructors

### MemoryUsageMetric

```
MemoryUsageMetric(
    mode: MemoryUsageMetric.Mode,
    subMetrics: List<MemoryUsageMetric.SubMetric> = listOf(
            SubMetric.HeapSize,
            SubMetric.RssAnon,
            SubMetric.RssFile,
            SubMetric.Gpu,
        ),
    processNameSuffix: String = "",
    metricNameSuffix: String = processNameSuffix.replace(oldValue = ":", newValue = "_")
)
```

| Parameters |
|---|---|
| `mode: https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric.Mode` | There are two modes for measurement - `Last`, which represents the last observed value during an iteration, and `Max`, which represents the largest sample observed per measurement. |
| `subMetrics: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/-list/index.html<https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric.SubMetric> = listOf( SubMetric.HeapSize, SubMetric.RssAnon, SubMetric.RssFile, SubMetric.Gpu, )` | By default, reports: - `memoryRssAnonKb` - Tracks anonymous resident set size memory. This represents memory allocated directly by the process---such as via malloc or `mmap`---that is not backed by any file on disk. It is often the primary indicator of the app's dynamic memory consumption. - `memoryRssAnonFileKb` - Tracks memory used to map files from disk into the process's address space. This includes shared libraries, dex files, and other resource assets loaded by the application. - `memoryHeapSizeKb` - Tracks the total size of the Android Runtime (ART) heap. These samples are typically captured immediately after a Garbage Collection (GC) event, providing a look at the "live" set of objects in the application's managed memory. - `memoryGpuKb` - Tracks the amount of GPU-specific memory allocated for the process. This is particularly useful for identifying high memory usage related to textures, shaders, or other graphics-heavy components. By passing a custom `subMetrics` list, you can enable other `https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric.SubMetric`s. |
| `processNameSuffix: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/index.html = ""` | A suffix appended to the app's package name for subprocesses. This is useful when there are separate subprocesses of the app. |
| `metricNameSuffix: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/index.html = processNameSuffix.replace(oldValue = ":", newValue = "_")` | A suffix appended to the metric names. Use this to distinguish metrics collected from different subprocesses in the app. Defaults to `https://developer.android.com/reference/kotlin/androidx/benchmark/macro/MemoryUsageMetric#processNameSuffix()` with ":" replaced by "_". |

## Public functions

### getMeasurements

```
open fun getMeasurements(
    captureInfo: Metric.CaptureInfo,
    traceSession: TraceProcessor.Session
): List<Metric.Measurement>
```

Get the metric result for a given iteration given information about the target process and a TraceProcessor session

```kotlin
import androidx.benchmark.macro.ExperimentalMetricApi
import androidx.benchmark.macro.TraceMetric
import androidx.benchmark.traceprocessor.TraceProcessor

/**
 * Calculates latency of sections where begin and end trace points are in different processes.
 *
 * @param beginPointName Name of begin tracepoint.
 * @param endPointName Name of end tracepoint.
 * @param eventName Name of the final metric that is spit out after the test run. The metric
 *   name will be {$eventName}LatencyMillis.
 */
@OptIn(ExperimentalMetricApi::class)
class CrossProcessLatencyMetricSample(
    private val beginPointName: String,
    private val endPointName: String,
    private val eventName: String,
) : TraceMetric() {
    @OptIn(ExperimentalMetricApi::class)
    override fun getMeasurements(
        captureInfo: CaptureInfo,
        traceSession: TraceProcessor.Session,
    ): List<Measurement> {
        val query =
            """
         INCLUDE perfetto module slices.with_context;
         SELECT
             event,
             ts2-ts1 AS latency_in_nanos
         FROM
         (
           (SELECT
               ts AS ts1,
               "event" AS event,
               LOWER(TRIM(process_name)) as process_name_1
               FROM thread_slice WHERE name = '${beginPointName}'
           )
           LEFT JOIN
           (SELECT
               ts AS ts2,
               "event" AS event,
               LOWER(TRIM(process_name)) as process_name_2
               FROM thread_slice WHERE name = '${endPointName}'
           )
           USING (event)
         )
           """
                .trimIndent() // maybe add checks for process name etc too in query

        val rowSequence = traceSession.query(query)
        // First row (or null) is returned.
        val latencyResultNanos = rowSequence.firstOrNull()?.long("latency_in_nanos")
        return if (latencyResultNanos != null) {
            listOf(Measurement(eventName + "LatencyMillis", latencyResultNanos / 1_000_000.0))
        } else {
            emptyList()
        }
    }
}
```