1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.os; 18 19 20 import android.perftests.utils.BenchmarkState; 21 import android.perftests.utils.PerfStatusReporter; 22 23 import androidx.test.filters.LargeTest; 24 import androidx.test.runner.AndroidJUnit4; 25 26 import com.android.internal.os.CachedDeviceState; 27 import com.android.internal.os.LooperStats; 28 29 import org.junit.After; 30 import org.junit.Before; 31 import org.junit.Rule; 32 import org.junit.Test; 33 import org.junit.runner.RunWith; 34 35 /** 36 * Performance tests for {@link LooperStats}. 37 */ 38 @RunWith(AndroidJUnit4.class) 39 @LargeTest 40 public class LooperStatsPerfTest { 41 private static final int DISTINCT_MESSAGE_COUNT = 1000; 42 43 @Rule 44 public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); 45 private LooperStats mStats; 46 private CachedDeviceState mDeviceState; 47 private HandlerThread mThread; 48 private Message[] mMessages = new Message[DISTINCT_MESSAGE_COUNT]; 49 50 @Before 51 public void setUp() { 52 mStats = new LooperStats(1, DISTINCT_MESSAGE_COUNT - 1); 53 mDeviceState = new CachedDeviceState(false, false); 54 mStats.setDeviceState(mDeviceState.getReadonlyClient()); 55 // The tests are all single-threaded. HandlerThread is created to allow creating Handlers. 56 mThread = new HandlerThread("UnusedThread"); 57 mThread.start(); 58 for (int i = 0; i < DISTINCT_MESSAGE_COUNT; i++) { 59 mMessages[i] = mThread.getThreadHandler().obtainMessage(i); 60 } 61 } 62 63 @After 64 public void tearDown() { 65 mThread.quit(); 66 } 67 68 @Test 69 public void timeHundredPercentSampling() { 70 mStats.setSamplingInterval(1); 71 runScenario(); 72 } 73 74 @Test 75 public void timeOnePercentSampling() { 76 mStats.setSamplingInterval(100); 77 runScenario(); 78 } 79 80 @Test 81 public void timeCollectionDisabled() { 82 // We do not collect data on charger. 83 mDeviceState.setCharging(true); 84 runScenario(); 85 } 86 87 private void runScenario() { 88 final BenchmarkState state = mPerfStatusReporter.getBenchmarkState(); 89 while (state.keepRunning()) { 90 for (int i = 0; i < DISTINCT_MESSAGE_COUNT; i++) { 91 Object token = mStats.messageDispatchStarting(); 92 mStats.messageDispatched(token, mMessages[i]); 93 } 94 } 95 } 96 } 97