Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(34)

Side by Side Diff: build/android/apksize.py

Issue 1397553002: [Android] Apk size tool. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: chartjson conversion step one Created 5 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 #!/usr/bin/env python
2 # Copyright 2015 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 import argparse
7 import collections
8 import logging
9 import os
10 import sys
11 import zipfile
12
13 from pylib import constants
14
15 sys.path.append(os.path.join(constants.DIR_SOURCE_ROOT, 'build', 'util', 'lib',
16 'common'))
17 import perf_tests_results_helper # pylint: disable=import-error
18
19 _BASE_CHART = {
20 'format_version': '0.1',
21 'benchmark_name': 'apk_size',
22 'benchmark_description': 'APK size information.',
23 'trace_rerun_options': [],
24 'charts': {}
25 }
26
27
28 # TODO(rnephew): Add support for split apks.
29 class ApkSizeInfo(object):
30
31 def __init__(self, path):
32 """ApkSizeInfo constructor.
33
34 Args:
35 path: Path to apk.
36 """
37 if not os.path.isfile(path):
38 raise IOError('Not a valid file path for apk.')
39 if not os.access(path, os.R_OK):
40 raise IOError('File is not readable.')
41 if not zipfile.is_zipfile(path):
42 raise TypeError('Not a valid apk')
43 logging.info('APK: %s', path)
44 self._apk_size = os.path.getsize(path)
45 self._zipfile = zipfile.ZipFile(path, 'r')
46 self._processed_files = None
47 self._compressed_size = 0
48 self._total_files = 0
49 self._uncompressed_size = 0
50 self._ProcessFiles()
51
52 def _ProcessFiles(self):
53 """Uses zipinfo to process apk file information."""
54 INITIAL_FILE_EXTENSION_INFO = {
55 'number': 0,
56 'compressed_bytes': 0,
57 'uncompressed_bytes': 0
58 }
59 self._processed_files = collections.defaultdict(
60 lambda: dict(INITIAL_FILE_EXTENSION_INFO))
61
62 for f in self._zipfile.infolist():
63 _, file_ext = os.path.splitext(f.filename)
64 file_ext = file_ext[1:] # Drop . from extension.
65
66 self._compressed_size += f.compress_size
67 self._total_files += 1
68 self._uncompressed_size += f.file_size
69 self._processed_files[file_ext]['number'] += 1
70 self._processed_files[file_ext]['compressed_bytes'] += f.compress_size
71 self._processed_files[file_ext]['uncompressed_bytes'] += f.file_size
72 return self._processed_files
73
74 def Compare(self, other_apk):
75 """Compares size information of two apks.
76
77 Args:
78 other_apk: ApkSizeInfo instance to compare size against.
79
80 Returns:
81 Dictionary of comparision results.
82 """
83 if not isinstance(other_apk, type(self)):
84 raise TypeError('Must pass it an ApkSizeInfo object')
85
86 other_lib_compressed = other_apk.processed_files['so']['compressed_bytes']
87 other_lib_uncompressed = (
88 other_apk.processed_files['so']['uncompressed_bytes'])
89 this_lib_compressed = self._processed_files['so']['compressed_bytes']
90 this_lib_uncompressed = self._processed_files['so']['uncompressed_bytes']
91
92 # TODO(rnephew) This will be made obsolete with modern and legacy apks being
93 # separate, a new method to compare will be required eventually.
94 return collections.OrderedDict([
95 ('APK_size_reduction',
96 other_apk.compressed_size - self.compressed_size),
97 ('ARM32_Legacy_install_or_upgrade_reduction',
98 (other_lib_compressed - this_lib_compressed) +
99 (other_lib_uncompressed - this_lib_uncompressed)),
100 ('ARM32_Legacy_system_image_reduction',
101 other_lib_compressed - this_lib_compressed),
102 ('ARM32_Modern_ARM64_install_or_upgrade_reduction',
103 other_lib_uncompressed - this_lib_uncompressed),
104 ('ARM32_Modern_ARM64_system_image_reduction',
105 other_lib_uncompressed - this_lib_uncompressed),
106 ])
107
108 @property
109 def apk_size(self):
110 return self._apk_size
111
112 @property
113 def compressed_size(self):
114 return self._compressed_size
115
116 @property
117 def total_files(self):
118 return self._total_files
119
120 @property
121 def uncompressed_size(self):
122 return self._uncompressed_size
123
124 @property
125 def processed_files(self):
126 return self._processed_files
127
128 def add_value(chart_data, graph_title, trace_title, value, units,
129 improvement_direction='down', important=True):
130 chart_data['charts'].setdefault(graph_title, {})
131 chart_data['charts'][graph_title][trace_title] = {
132 'type': 'scalar',
133 'value': value,
134 'units': units,
135 'imporvement_direction': improvement_direction,
136 'important': important
137 }
138
139 def chartjson_size_info(apk):
140 """Sends size information to perf dashboard.
141
142 Args:
143 apk: ApkSizeInfo object
144 """
145 data = _BASE_CHART.copy()
146 files = apk.processed_files
147 add_value(data, 'files', 'total', apk.total_files, 'count')
148 add_value(data, 'size', 'total_size_compressed', apk.compressed_size, 'bytes')
149 add_value(data, 'size', 'total_size_uncompressed', apk.uncompressed_size,
150 'bytes')
151 add_value(data, 'size', 'apk_overhead', apk.apk_size - apk.compressed_size,
152 'bytes')
153 for ext in files:
154 add_value(data, 'files', ext, files[ext]['number'], 'count')
155 add_value(data, 'size_compressed', ext, files[ext]['compressed_bytes'],
156 'bytes')
157 add_value(data, 'size_uncompressed', ext, files[ext]['uncompressed_bytes'],
158 'bytes')
159
160 def print_human_readable_size_info(apk):
161 """Prints size information in human readable format.
162
163 Args:
164 apk: ApkSizeInfo object
165 """
166 files = apk.processed_files
167 logging.critical('Stats for files as they exist within the apk:')
168 for ext in files:
169 logging.critical(' %-8s %s bytes in %s files', ext,
170 files[ext]['compressed_bytes'], files[ext]['number'])
171 logging.critical('--------------------------------------')
172 logging.critical(
173 'All Files: %s bytes in %s files', apk.compressed_size, apk.total_files)
174 logging.critical('APK Size: %s', apk.apk_size)
175 logging.critical('APK overhead: %s', apk.apk_size - apk.compressed_size)
176 logging.critical('--------------------------------------')
177 logging.critical('Stats for files when extracted from the apk:')
178 for ext in files:
179 logging.critical(' %-8s %s bytes in %s files', ext,
180 files[ext]['uncompressed_bytes'], files[ext]['number'])
181 logging.critical('--------------------------------------')
182 logging.critical(
183 'All Files: %s bytes in %s files', apk.uncompressed_size, apk.total_files)
184
185 def chartjson_compare(compare_dict):
186 """Sends size comparison between two apks to perf dashboard.
187
188 Args:
189 compare_dict: Dictionary returned from APkSizeInfo.Compare()
190 """
191 data = _BASE_CHART.copy()
192 for key, value in compare_dict.iteritems():
193 add_value(data, 'compare', key, value, 'bytes')
194
195 def print_human_readable_compare(compare_dict):
196 """Prints size comparison between two apks in human readable format.
197
198 Args:
199 compare_dict: Dictionary returned from ApkSizeInfo.Compare()
200 """
201 for key, value in compare_dict.iteritems():
202 logging.critical(' %-50s %s bytes', key, value)
203
204 def main():
205 parser = argparse.ArgumentParser()
206 parser.add_argument('file_path')
207 parser.add_argument('-c', '--compare', help=('APK to compare against.'))
208 parser.add_argument('-d', '--perf-dashboard-output', action='store_true',
perezju 2015/10/29 09:56:23 You've got nearly everything ready. The last bit t
jbudorick 2015/10/29 13:16:40 I would lean toward the dummy --device argument.
rnephew (Reviews Here) 2015/10/29 21:45:51 Done.
209 help=('Sets it to return data in bot readable format'))
210 args = parser.parse_args()
211
212 apk = ApkSizeInfo(args.file_path)
213 if args.compare:
214 compare_dict = apk.Compare(ApkSizeInfo(args.compare))
215 if args.perf_dashboard_output:
216 chartjson_compare(compare_dict)
217 else:
218 print_human_readable_compare(compare_dict)
219 else:
220 if args.perf_dashboard_output:
221 chartjson_size_info(apk)
222 else:
223 print_human_readable_size_info(apk)
224
225 if __name__ == '__main__':
226 sys.exit(main())
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698