1#!/usr/bin/env python
2#
3# Copyright (C) 2016 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18import logging
19
20from vts.proto import VtsReportMessage_pb2 as ReportMsg
21from vts.runners.host import asserts
22from vts.runners.host import base_test
23from vts.runners.host import const
24from vts.runners.host import test_runner
25from vts.utils.python.controllers import android_device
26from vts.utils.python.cpu import cpu_frequency_scaling
27
28# number of threads to use when running the throughput tests on target.
29_THREAD_LIST = [2, 3, 4, 5, 7, 10, 30, 50, 70, 100]
30
31_ITERATIONS_PER_SECOND = "iterations_per_second"
32_TIME_AVERAGE = "time_average"
33_TIME_WORST = "time_worst"
34_TIME_BEST = "time_best"
35_TIME_PERCENTILE = "time_percentile"
36
37
38class HwBinderThroughputBenchmark(base_test.BaseTestClass):
39    """A test case for the binder throughput benchmarking."""
40
41    def setUpClass(self):
42        required_params = ["hidl_hal_mode"]
43        self.getUserParams(required_params)
44        self.dut = self.android_devices[0]
45        self._cpu_freq = cpu_frequency_scaling.CpuFrequencyScalingController(self.dut)
46        self._cpu_freq.DisableCpuScaling()
47
48    def setUp(self):
49        self._cpu_freq.SkipIfThermalThrottling(retry_delay_secs=30)
50
51    def tearDown(self):
52        self._cpu_freq.SkipIfThermalThrottling()
53
54    def tearDownClass(self):
55        self._cpu_freq.EnableCpuScaling()
56
57    def testRunBenchmark32Bit(self):
58        """A test case which runs the 32-bit benchmark."""
59        self.RunBenchmarkAndReportResult(32)
60
61    def testRunBenchmark64Bit(self):
62        """A test case which runs the 64-bit benchmark."""
63        self.RunBenchmarkAndReportResult(64)
64
65    def RunBenchmarkAndReportResult(self, bits):
66        """Runs the native binary and stores its result to the web DB.
67
68        Args:
69            bits: integer (32 or 64), the number of bits in a word chosen
70                  at the compile time (e.g., 32- vs. 64-bit library).
71        """
72        labels = []
73        iterations_per_second = []
74        time_average = []
75        time_best = []
76        time_worst = []
77        time_percentile_50 = []
78        time_percentile_90 = []
79        time_percentile_95 = []
80        time_percentile_99 = []
81
82        for thread in _THREAD_LIST:
83            result = self.RunBenchmark(bits, thread)
84            labels.append("%s_thread" % thread)
85            iterations_per_second.append(result["iterations_per_second"])
86            time_average.append(result["time_average"])
87            time_best.append(result["time_best"])
88            time_worst.append(result["time_worst"])
89            time_percentile_50.append(result["time_percentile"][50])
90            time_percentile_90.append(result["time_percentile"][90])
91            time_percentile_95.append(result["time_percentile"][95])
92            time_percentile_99.append(result["time_percentile"][99])
93
94        # To upload to the web DB.
95        self.web.AddProfilingDataLabeledVector(
96            "hwbinder_throughput_iterations_per_second_%sbits" % bits,
97            labels, iterations_per_second, x_axis_label="Number of Threads",
98            y_axis_label="HwBinder RPC Iterations Per Second",
99            regression_mode=ReportMsg.VTS_REGRESSION_MODE_DISABLED)
100
101        self.web.AddProfilingDataLabeledVector(
102            "hwbinder_throughput_time_average_ns_%sbits" % bits,
103            labels, time_average, x_axis_label="Number of Threads",
104            y_axis_label="HwBinder RPC Time - Average (nanoseconds)",
105            regression_mode=ReportMsg.VTS_REGRESSION_MODE_DISABLED)
106        self.web.AddProfilingDataLabeledVector(
107            "hwbinder_throughput_time_best_ns_%sbits" % bits,
108            labels, time_best, x_axis_label="Number of Threads",
109            y_axis_label="HwBinder RPC Time - Best Case (nanoseconds)")
110        self.web.AddProfilingDataLabeledVector(
111            "hwbinder_throughput_time_worst_ns_%sbits" % bits,
112            labels, time_worst, x_axis_label="Number of Threads",
113            y_axis_label="HwBinder RPC Time - Worst Case (nanoseconds)",
114            regression_mode=ReportMsg.VTS_REGRESSION_MODE_DISABLED)
115
116        self.web.AddProfilingDataLabeledVector(
117            "hwbinder_throughput_time_50percentile_ns_%sbits" % bits,
118            labels, time_percentile_50, x_axis_label="Number of Threads",
119            y_axis_label="HwBinder RPC Time - 50 Percentile (nanoseconds)",
120            regression_mode=ReportMsg.VTS_REGRESSION_MODE_DISABLED)
121        self.web.AddProfilingDataLabeledVector(
122            "hwbinder_throughput_time_90percentile_ns_%sbits" % bits,
123            labels, time_percentile_90, x_axis_label="Number of Threads",
124            y_axis_label="HwBinder RPC Time - 90 Percentile (nanoseconds)",
125            regression_mode=ReportMsg.VTS_REGRESSION_MODE_DISABLED)
126        self.web.AddProfilingDataLabeledVector(
127            "hwbinder_throughput_time_95percentile_ns_%sbits" % bits,
128            labels, time_percentile_95, x_axis_label="Number of Threads",
129            y_axis_label="HwBinder RPC Time - 95 Percentile (nanoseconds)",
130            regression_mode=ReportMsg.VTS_REGRESSION_MODE_DISABLED)
131        self.web.AddProfilingDataLabeledVector(
132            "hwbinder_throughput_time_99percentile_ns_%sbits" % bits,
133            labels, time_percentile_99, x_axis_label="Number of Threads",
134            y_axis_label="HwBinder RPC Time - 99 Percentile (nanoseconds)",
135            regression_mode=ReportMsg.VTS_REGRESSION_MODE_DISABLED)
136
137    def RunBenchmark(self, bits, threads):
138        """Runs the native binary and parses its result.
139
140        Args:
141            bits: integer (32 or 64), the number of bits in a word chosen
142                  at the compile time (e.g., 32- vs. 64-bit library).
143            threads: positive integer, the number of threads to use.
144
145        Returns:
146            a dict which contains the benchmarking result where the keys are:
147                'iterations_per_second', 'time_average', 'time_worst',
148                'time_best', 'time_percentile'.
149        """
150        # Runs the benchmark.
151        logging.info("Start to run the benchmark with HIDL mode %s (%s bit mode)",
152                     self.hidl_hal_mode, bits)
153        binary = "/data/local/tmp/%s/hwbinderThroughputTest%s" % (bits, bits)
154
155        results = self.dut.shell.Execute(
156            ["chmod 755 %s" % binary,
157             "VTS_ROOT_PATH=/data/local/tmp " \
158             "LD_LIBRARY_PATH=/system/lib%s:/data/local/tmp/%s/hw:"
159             "/data/local/tmp/%s:"
160             "$LD_LIBRARY_PATH %s -m %s -w %s" % (bits, bits, bits, binary, self.hidl_hal_mode.encode("utf-8"), threads)])
161
162        # Parses the result.
163        asserts.assertEqual(len(results[const.STDOUT]), 2)
164        logging.info("stderr: %s", results[const.STDERR][1])
165        stdout_lines = results[const.STDOUT][1].split("\n")
166        logging.info("stdout: %s", stdout_lines)
167
168        asserts.assertFalse(
169            any(results[const.EXIT_CODE]),
170            "testRunBenchmark%sBit(%s thread) failed." % (bits, threads))
171
172        # To upload to the web DB.
173        summary = {}
174        index = next(i for i, string in enumerate(stdout_lines)
175                     if "iterations per sec:" in string)
176        summary[_ITERATIONS_PER_SECOND] = int(float(
177            stdout_lines[index].replace("iterations per sec: ", "")))
178        # an example is 'iterations per sec: 34868.7'
179
180        index = next(i for i, string in enumerate(stdout_lines)
181                     if "average:" in string)
182        stats_string = stdout_lines[index].split()
183        # an example is 'average:0.0542985ms worst:0.314584ms best:0.02651ms'
184        summary[_TIME_AVERAGE] = int(float(
185            stats_string[0].replace(
186                "average:", "").replace("ms", "")) * 1000000)
187        summary[_TIME_WORST] = int(float(
188            stats_string[1].replace("worst:", "").replace("ms", "")) * 1000000)
189        summary[_TIME_BEST] = int(float(
190            stats_string[2].replace("best:", "").replace("ms", "")) * 1000000)
191
192        index = next(i for i, string in enumerate(stdout_lines)
193                     if "50%: " in string)
194        percentiles_string = stdout_lines[index].split()
195        summary[_TIME_PERCENTILE] = {}
196        summary[_TIME_PERCENTILE][50] = int(float(percentiles_string[1])
197                                            * 1000000)
198        summary[_TIME_PERCENTILE][90] = int(float(percentiles_string[3])
199                                            * 1000000)
200        summary[_TIME_PERCENTILE][95] = int(float(percentiles_string[5])
201                                            * 1000000)
202        summary[_TIME_PERCENTILE][99] = int(float(percentiles_string[7])
203                                            * 1000000)
204        return summary
205
206if __name__ == "__main__":
207    test_runner.main()
208