• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 com.android.internal.os;
18 
19 import static com.google.common.truth.Truth.assertThat;
20 
21 import android.content.Context;
22 import android.os.BatteryStatsManager;
23 import android.os.BatteryUsageStats;
24 import android.os.UidBatteryConsumer;
25 import android.perftests.utils.BenchmarkState;
26 import android.perftests.utils.PerfStatusReporter;
27 
28 import androidx.test.InstrumentationRegistry;
29 import androidx.test.filters.LargeTest;
30 import androidx.test.runner.AndroidJUnit4;
31 
32 import org.junit.Rule;
33 import org.junit.Test;
34 import org.junit.runner.RunWith;
35 
36 import java.util.List;
37 
38 @RunWith(AndroidJUnit4.class)
39 @LargeTest
40 public class BatteryUsageStatsPerfTest {
41 
42     @Rule
43     public final PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
44 
45     /**
46      * Measures the performance of {@link BatteryStatsManager#getBatteryUsageStats()},
47      * which triggers a battery stats sync on every iteration.
48      */
49     @Test
testGetBatteryUsageStats()50     public void testGetBatteryUsageStats() {
51         final Context context = InstrumentationRegistry.getContext();
52         final BatteryStatsManager batteryStatsManager =
53                 context.getSystemService(BatteryStatsManager.class);
54 
55         final BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
56         while (state.keepRunning()) {
57             BatteryUsageStats batteryUsageStats = batteryStatsManager.getBatteryUsageStats();
58 
59             state.pauseTiming();
60 
61             List<UidBatteryConsumer> uidBatteryConsumers =
62                     batteryUsageStats.getUidBatteryConsumers();
63             double power = 0;
64             for (int i = 0; i < uidBatteryConsumers.size(); i++) {
65                 UidBatteryConsumer uidBatteryConsumer = uidBatteryConsumers.get(i);
66                 power += uidBatteryConsumer.getConsumedPower();
67             }
68 
69             assertThat(power).isGreaterThan(0.0);
70 
71             state.resumeTiming();
72         }
73     }
74 }
75