BenchmarkRule

public final class BenchmarkRule


JUnit rule for benchmarking code on an Android device.

In Kotlin, benchmark with measureRepeated:

@get:Rule
val benchmarkRule = BenchmarkRule();

@Test
fun myBenchmark() {
...
benchmarkRule.measureRepeated {
doSomeWork()
}
...
}

In Java, use getState():

@Rule
public BenchmarkRule benchmarkRule = new BenchmarkRule();

@Test
public void myBenchmark() {
...
BenchmarkState state = benchmarkRule.getState();
while (state.keepRunning()) {
doSomeWork();
}
...
}

Benchmark results will be output:

  • Summary in AndroidStudio in the test log

  • In JSON format, on the host

  • In simple form in Logcat with the tag "Benchmark"

  • To the instrumentation status result Bundle on the gradle command line

Every test in the Class using this @Rule must contain a single benchmark.

Summary

Nested types

BenchmarkRule.Scope

Handle used for controlling timing during measureRepeated.

Public constructors

Public methods

@NonNull Statement
apply(@NonNull Statement base, @NonNull Description description)
final @NonNull BenchmarkState

Object used for benchmarking in Java.

Extension functions

final void

Benchmark a block of code.

Public constructors

BenchmarkRule

public final BenchmarkRule()

Public methods

apply

@NonNull
public Statement apply(@NonNull Statement base, @NonNull Description description)

getState

@NonNull
public final BenchmarkState getState()

Object used for benchmarking in Java.

@Rule
public BenchmarkRule benchmarkRule = new BenchmarkRule();

@Test
public void myBenchmark() {
...
BenchmarkState state = benchmarkRule.getBenchmarkState();
while (state.keepRunning()) {
doSomeWork();
}
...
}
Throws
kotlin.IllegalStateException

if the BenchmarkRule isn't correctly applied to a test.

Extension functions

BenchmarkRuleKt.measureRepeated

@NonNull
public final void BenchmarkRuleKt.measureRepeated(
    @NonNull BenchmarkRule receiver,
    @NonNull Function1<@NonNull BenchmarkRule.ScopeUnit> block
)

Benchmark a block of code.

@get:Rule
val benchmarkRule = BenchmarkRule();

@Test
fun myBenchmark() {
...
benchmarkRule.measureRepeated {
doSomeWork()
}
...
}
Parameters
@NonNull Function1<@NonNull BenchmarkRule.ScopeUnit> block

The block of code to benchmark.