Microbenchmark và Hilt

Nhiều ứng dụng sử dụng Hilt để chèn các hành vi khác nhau vào các biến thể bản dựng khác nhau. Điều này có thể đặc biệt hữu ích khi bạn đo điểm chuẩn vi mô cho ứng dụng vì cho phép bạn chuyển đổi một thành phần có thể làm sai lệch kết quả. Ví dụ: đoạn mã sau đây cho thấy một kho lưu trữ tìm nạp và sắp xếp danh sách tên:

Kotlin

class PeopleRepository @Inject constructor(
    @Kotlin private val dataSource: NetworkDataSource,
    @Dispatcher(DispatcherEnum.IO) private val dispatcher: CoroutineDispatcher
) {
    private val _peopleLiveData = MutableLiveData<List<Person>>()

    val peopleLiveData: LiveData<List<Person>>
        get() = _peopleLiveData

    suspend fun update() {
        withContext(dispatcher) {
            _peopleLiveData.postValue(
                dataSource.getPeople()
                    .sortedWith(compareBy({ it.lastName }, { it.firstName }))
            )
        }
    }
}}

Java

public class PeopleRepository {

    private final MutableLiveData<List<Person>> peopleLiveData = new MutableLiveData<>();

    private final NetworkDataSource dataSource;

    public LiveData<List<Person>> getPeopleLiveData() {
        return peopleLiveData;
    }

    @Inject
    public PeopleRepository(NetworkDataSource dataSource) {
        this.dataSource = dataSource;
    }

    private final Comparator<Person> comparator = Comparator.comparing(Person::getLastName)
            .thenComparing(Person::getFirstName);

    public void update() {
        Runnable task = new Runnable() {

            @Override
            public void run() {
                peopleLiveData.postValue(
                        dataSource.getPeople()
                                .stream()
                                .sorted(comparator)
                                .collect(Collectors.toList())
                );
            }
        };
        new Thread(task).start();
    }
}

Nếu bạn thêm lệnh gọi mạng khi đo điểm chuẩn, hãy triển khai lệnh gọi mạng giả để nhận được kết quả chính xác hơn.

Việc đưa lệnh gọi mạng thực tế vào khi đo điểm chuẩn sẽ khiến kết quả đo điểm chuẩn khó diễn giải hơn. Các lệnh gọi mạng có thể chịu ảnh hưởng của nhiều yếu tố bên ngoài và thời lượng của các lệnh gọi này có thể thay đổi giữa các lần lặp lại khi chạy phép đo điểm chuẩn. Thời gian thực hiện lệnh gọi mạng có thể lâu hơn thời gian sắp xếp.

Triển khai lệnh gọi mạng giả bằng Hilt

Lệnh gọi đến dataSource.getPeople(), như trong ví dụ trước, chứa một lệnh gọi mạng. Tuy nhiên, thực thể NetworkDataSource được chèn bằng Hilt và bạn có thể thay thế thực thể đó bằng cách triển khai giả sau đây để đo điểm chuẩn:

Kotlin

class FakeNetworkDataSource @Inject constructor(
    private val people: List<Person>
) : NetworkDataSource {
    override fun getPeople(): List<Person> = people
}

Java

public class FakeNetworkDataSource implements NetworkDataSource{

    private List<Person> people;

    @Inject
    public FakeNetworkDataSource(List<Person> people) {
        this.people = people;
    }

    @Override
    public List<Person> getPeople() {
        return people;
    }
}

Lệnh gọi mạng giả này được thiết kế để chạy nhanh nhất có thể khi bạn gọi phương thức getPeople(). Để Hilt có thể chèn phần phụ thuộc này, nhà cung cấp sau đây sẽ được sử dụng:

Kotlin

@Module
@InstallIn(SingletonComponent::class)
object FakekNetworkModule {

    @Provides
    @Kotlin
    fun provideNetworkDataSource(@ApplicationContext context: Context): NetworkDataSource {
        val data = context.assets.open("fakedata.json").use { inputStream ->
            val bytes = ByteArray(inputStream.available())
            inputStream.read(bytes)

            val gson = Gson()
            val type: Type = object : TypeToken<List<Person>>() {}.type
            gson.fromJson<List<Person>>(String(bytes), type)
        }
        return FakeNetworkDataSource(data)
    }
}

Java

@Module
@InstallIn(SingletonComponent.class)
public class FakeNetworkModule {

    @Provides
    @Java
    NetworkDataSource provideNetworkDataSource(
            @ApplicationContext Context context
    ) {
        List<Person> data = new ArrayList<>();
        try (InputStream inputStream = context.getAssets().open("fakedata.json")) {
            int size = inputStream.available();
            byte[] bytes = new byte[size];
            if (inputStream.read(bytes) == size) {
                Gson gson = new Gson();
                Type type = new TypeToken<ArrayList<Person>>() {
                }.getType();
                data = gson.fromJson(new String(bytes), type);

            }
        } catch (IOException e) {
            // Do something
        }
        return new FakeNetworkDataSource(data);
    }
}

Dữ liệu được tải từ các thành phần bằng cách sử dụng lệnh gọi I/O có độ dài có thể thay đổi. Tuy nhiên, việc này được thực hiện trong quá trình khởi chạy và sẽ không gây ra bất kỳ sự bất thường nào khi getPeople() được gọi trong quá trình đo điểm chuẩn.

Một số ứng dụng đã sử dụng dữ liệu giả trên bản gỡ lỗi để xoá mọi phần phụ thuộc của phần phụ trợ. Tuy nhiên, bạn cần đo điểm chuẩn trên một bản dựng càng gần với bản phát hành càng tốt. Phần còn lại của tài liệu này sử dụng cấu trúc nhiều mô-đun, nhiều biến thể như mô tả trong phần Thiết lập toàn bộ dự án.

Có 3 mô-đun:

  • benchmarkable: chứa mã để đo điểm chuẩn.
  • benchmark: chứa mã điểm chuẩn.
  • app: chứa mã ứng dụng còn lại.

Mỗi mô-đun trước đó đều có một biến thể bản dựng tên là benchmark cùng với các biến thể debug và release thông thường.

Định cấu hình mô-đun điểm chuẩn

Mã cho lệnh gọi mạng giả nằm trong nhóm tài nguyên debug của mô-đun benchmarkable và quá trình triển khai mạng đầy đủ nằm trong nhóm tài nguyên release của cùng một mô-đun. Tệp tài sản chứa dữ liệu do quá trình triển khai giả trả về nằm trong nhóm tài nguyên debug để tránh tình trạng tệp APK bị phình to trong bản dựng release. Biến thể benchmark cần dựa trên release và sử dụng nhóm tài nguyên debug. Cấu hình bản dựng cho biến thể benchmark của mô-đun benchmarkable chứa phương thức triển khai giả lập như sau:

Kotlin

android {
    ...
    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
        create("benchmark") {
            initWith(getByName("release"))
        }
    }
    ...
    sourceSets {
        getByName("benchmark") {
            java.setSrcDirs(listOf("src/debug/java"))
            assets.setSrcDirs(listOf("src/debug/assets"))
        }
    }
}

Groovy

android {
    ...
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
                'proguard-rules.pro'
            )
        }
        benchmark {
            initWith release
        }
    }
    ...
    sourceSets {
        benchmark {
            java.setSrcDirs ['src/debug/java']
            assets.setSrcDirs(listOf ['src/debug/assets']
        }
    }
}

Trong mô-đun benchmark, hãy thêm một trình chạy kiểm thử tuỳ chỉnh để tạo một Application cho các kiểm thử chạy trong đó hỗ trợ Hilt như sau:

Kotlin

class HiltBenchmarkRunner : AndroidBenchmarkRunner() {

    override fun newApplication(
        cl: ClassLoader?,
        className: String?,
        context: Context?
    ): Application {
        return super.newApplication(cl, HiltTestApplication::class.java.name, context)
    }
}

Java

public class JavaHiltBenchmarkRunner extends AndroidBenchmarkRunner {

    @Override
    public Application newApplication(
            ClassLoader cl,
            String className,
            Context context
    ) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return super.newApplication(cl, HiltTestApplication.class.getName(), context);
    }
}

Thao tác này giúp đối tượng Application (nơi chạy kiểm thử) mở rộng lớp HiltTestApplication. Thực hiện các thay đổi sau đối với cấu hình bản dựng:

Kotlin

plugins {
    alias(libs.plugins.android.library)
    alias(libs.plugins.benchmark)
    alias(libs.plugins.jetbrains.kotlin.android)
    alias(libs.plugins.kapt)
    alias(libs.plugins.hilt)
}

android {
    namespace = "com.example.hiltmicrobenchmark.benchmark"
    compileSdk = 34

    defaultConfig {
        minSdk = 24

        testInstrumentationRunner = "com.example.hiltbenchmark.HiltBenchmarkRunner"
    }

    testBuildType = "benchmark"
    buildTypes {
        debug {
            // Since isDebuggable can't be modified by Gradle for library modules,
            // it must be done in a manifest. See src/androidTest/AndroidManifest.xml.
            isMinifyEnabled = true
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "benchmark-proguard-rules.pro"
            )
        }
        create("benchmark") {
            initWith(getByName("debug"))
        }
    }
}

dependencies {
    androidTestImplementation(libs.bundles.hilt)
    androidTestImplementation(project(":benchmarkable"))
    implementation(libs.androidx.runner)
    androidTestImplementation(libs.androidx.junit)
    androidTestImplementation(libs.junit)
    implementation(libs.androidx.benchmark)
    implementation(libs.google.dagger.hiltTesting)
    kaptAndroidTest(libs.google.dagger.hiltCompiler)
    androidTestAnnotationProcessor(libs.google.dagger.hiltCompiler)
}

Groovy

plugins {
    alias libs.plugins.android.library
    alias libs.plugins.benchmark
    alias libs.plugins.jetbrains.kotlin.android
    alias libs.plugins.kapt
    alias libs.plugins.hilt
}

android {
    namespace = 'com.example.hiltmicrobenchmark.benchmark'
    compileSdk = 34

    defaultConfig {
        minSdk = 24

        testInstrumentationRunner 'com.example.hiltbenchmark.HiltBenchmarkRunner'
    }

    testBuildType "benchmark"
    buildTypes {
        debug {
            // Since isDebuggable can't be modified by Gradle for library modules,
            // it must be done in a manifest. See src/androidTest/AndroidManifest.xml.
            minifyEnabled true
            proguardFiles(
                getDefaultProguardFile('proguard-android-optimize.txt'),
                'benchmark-proguard-rules.pro'
            )
        }
        benchmark {
            initWith debug"
        }
    }
}

dependencies {
    androidTestImplementation libs.bundles.hilt
    androidTestImplementation project(':benchmarkable')
    implementation libs.androidx.runner
    androidTestImplementation libs.androidx.junit
    androidTestImplementation libs.junit
    implementation libs.androidx.benchmark
    implementation libs.google.dagger.hiltTesting
    kaptAndroidTest libs.google.dagger.hiltCompiler
    androidTestAnnotationProcessor libs.google.dagger.hiltCompiler
}

Ví dụ trước thực hiện những việc sau:

  • Áp dụng các trình bổ trợ gradle cần thiết cho bản dựng.
  • Chỉ định rằng trình chạy kiểm thử tuỳ chỉnh được dùng để chạy kiểm thử.
  • Chỉ định rằng biến thể benchmark là loại kiểm thử cho mô-đun này.
  • Thêm biến thể benchmark.
  • Thêm các phần phụ thuộc bắt buộc.

Bạn cần thay đổi testBuildType để đảm bảo Gradle tạo tác vụ connectedBenchmarkAndroidTest, tác vụ này sẽ thực hiện việc đo điểm chuẩn.

Tạo microbenchmark

Điểm chuẩn được triển khai như sau:

Kotlin

@RunWith(AndroidJUnit4::class)
@HiltAndroidTest
class PeopleRepositoryBenchmark {

    @get:Rule
    val benchmarkRule = BenchmarkRule()

    @get:Rule
    val hiltRule = HiltAndroidRule(this)

    private val latch = CountdownLatch(1)

    @Inject
    lateinit var peopleRepository: PeopleRepository

    @Before
    fun setup() {
        hiltRule.inject()
    }

    @Test
    fun benchmarkSort() {
        benchmarkRule.measureRepeated {
            runBlocking {
                benchmarkRule.getStart().pauseTiming()
                withContext(Dispatchers.Main.immediate) {
                    peopleRepository.peopleLiveData.observeForever(observer)
                }
                benchmarkRule.getStart().resumeTiming()
                peopleRepository.update()
                latch.await()
                assert(peopleRepository.peopleLiveData.value?.isNotEmpty() ?: false)
           }
        }
    }

    private val observer: Observer<List<Person>> = object : Observer<List<Person>> {
        override fun onChanged(people: List<Person>?) {
            peopleRepository.peopleLiveData.removeObserver(this)
            latch.countDown()
        }
    }
}

Java

@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
public class PeopleRepositoryBenchmark {
    @Rule
    public BenchmarkRule benchmarkRule = new BenchmarkRule();

    @Rule
    public HiltAndroidRule hiltRule = new HiltAndroidRule(this);

    private CountdownLatch latch = new CountdownLatch(1);

    @Inject
    JavaPeopleRepository peopleRepository;

    @Before
    public void setup() {
        hiltRule.inject();
    }

    @Test
    public void benchmarkSort() {
        BenchmarkRuleKt.measureRepeated(benchmarkRule, (Function1<BenchmarkRule.Scope, Unit>) scope -> {
            benchmarkRule.getState().pauseTiming();
            new Handler(Looper.getMainLooper()).post(() -> {
                awaitValue(peopleRepository.getPeopleLiveData());
            });
            benchmarkRule.getState().resumeTiming();
            peopleRepository.update();
            try {
                latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            assert (!peopleRepository.getPeopleLiveData().getValue().isEmpty());
            return Unit.INSTANCE;
        });
    }

    private <T> void awaitValue(LiveData<T> liveData) {
        Observer<T> observer = new Observer<T>() {
            @Override
            public void onChanged(T t) {
                liveData.removeObserver(this);
                latch.countDown();
            }
        };
        liveData.observeForever(observer);
        return;
    }
}

Ví dụ trước tạo quy tắc cho cả điểm chuẩn và Hilt. benchmarkRule thực hiện việc tính thời gian của điểm chuẩn. hiltRule thực hiện việc chèn phần phụ thuộc trên lớp kiểm thử điểm chuẩn. Bạn phải gọi phương thức inject() của quy tắc Hilt trong hàm @Before để thực hiện chèn trước khi chạy bất kỳ kiểm thử riêng lẻ nào.

Bản thân điểm chuẩn sẽ tạm dừng tính thời gian trong khi trình quan sát LiveData được đăng ký. Sau đó, lớp này sử dụng một chốt để đợi cho đến khi LiveData được cập nhật trước khi hoàn tất. Vì quá trình sắp xếp được chạy trong khoảng thời gian giữa thời điểm peopleRepository.update() được gọi và thời điểm LiveData nhận được bản cập nhật, nên thời lượng sắp xếp được đưa vào thời gian đo điểm chuẩn.

Chạy microbenchmark

Chạy điểm chuẩn bằng ./gradlew :benchmark:connectedBenchmarkAndroidTest để thực hiện điểm chuẩn qua nhiều lần lặp lại và in dữ liệu thời gian vào Logcat:

PeopleRepositoryBenchmark.log[Metric (timeNs) results: median 613408.3952380952, min 451949.30476190476, max 1412143.5142857144, standardDeviation: 273221.2328680522...

Ví dụ trước cho thấy kết quả điểm chuẩn từ 0,6 mili giây đến 1,4 mili giây để chạy thuật toán sắp xếp trên danh sách gồm 1.000 mục. Tuy nhiên, nếu bạn đưa lệnh gọi mạng vào điểm chuẩn, thì phương sai giữa các lần lặp lại sẽ lớn hơn thời gian mà quá trình sắp xếp tự chạy, do đó cần tách biệt quá trình sắp xếp khỏi lệnh gọi mạng.

Bạn luôn có thể cải tiến mã để dễ dàng chạy riêng quy trình sắp xếp, nhưng nếu đã sử dụng Hilt, bạn có thể dùng Hilt để chèn dữ liệu giả nhằm đo điểm chuẩn.