PageRenderTime 52ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/run_comparison.py

https://gitlab.com/0072016/fbphp-
Python | 308 lines | 231 code | 33 blank | 44 comment | 9 complexity | 98d805be253f5c05aedd7dc50f87b15c MD5 | raw file
  1. #!/usr/bin/env python
  2. # This file provided by Facebook is for non-commercial testing and evaluation
  3. # purposes only. Facebook reserves all rights not expressly granted.
  4. #
  5. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  8. # FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  9. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  10. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  11. """
  12. This script builds and runs the comparison app, switching from one library to the next,
  13. taking measurements as it goes, and outputs the results neatly.
  14. Due to a bug, you must specify the CPU when running the script.
  15. Use -c armeabi-v7a for most phones. Use -c armeabi for ARM v5-6 phones, or
  16. -c arm64 for 64-bit ARM devices. Some emulators and tablets will need -c x86.
  17. To select a subset of the libraries, use the -s option with a
  18. space-separated list. Available options are fresco, fresco-okhttp,
  19. glide, volley, drawee-volley, uil, picasso, and aquery.
  20. To see the comparison for only network or local images, use -d network or -d local.
  21. Note that Volley does not support local images, and fresco and fresco-okhttp
  22. are identical for local images.
  23. Results will vary based on the the device, the network conditions and the mix of images available.
  24. Example: to run a local-only comparison of fresco and picasso on an ARM v7 device:
  25. ./run_comparison.py -s fresco picasso -d local -c armeabi-v7a
  26. """
  27. from __future__ import absolute_import
  28. from __future__ import division
  29. from __future__ import print_function
  30. from __future__ import unicode_literals
  31. import argparse
  32. import glob
  33. import os
  34. import re
  35. import tempfile
  36. from collections import namedtuple
  37. from subprocess import check_call, PIPE, Popen
  38. """ List of tested libraries """
  39. TESTS = (
  40. 'fresco',
  41. 'fresco-okhttp',
  42. 'glide',
  43. 'picasso',
  44. 'uil',
  45. 'volley',
  46. 'drawee-volley',
  47. 'aquery',
  48. )
  49. TEST_SOURCES = (
  50. 'network',
  51. 'local'
  52. )
  53. ABIS = (
  54. 'arm64-v8a',
  55. 'armeabi',
  56. 'armeabi-v7a',
  57. 'x86',
  58. 'x86_64'
  59. )
  60. """ Appends test class name to method name """
  61. TEST_PATTERN = 'test{}{}'
  62. """ Named tuple containing relevant numbers reported by a test """
  63. Stats = namedtuple('Stats', [
  64. 'success_wait_times',
  65. 'failure_wait_times',
  66. 'cancellation_wait_times',
  67. 'java_heap_sizes',
  68. 'native_heap_sizes',
  69. 'skipped_frames'])
  70. def parse_args():
  71. parser = argparse.ArgumentParser(
  72. description='Runs comparison test and processes results')
  73. parser.add_argument('-s', '--scenarios', choices=TESTS, nargs='+')
  74. parser.add_argument('-d', '--sources', choices=TEST_SOURCES, nargs='+')
  75. parser.add_argument('-c', '--cpu', choices=ABIS, required=True)
  76. return parser.parse_args()
  77. def start_subprocess(command, **kwargs):
  78. """ Starts subprocess after printing command to stdout. """
  79. return Popen(command.split(), **kwargs)
  80. def run_command(command):
  81. """ Runs given command and waits for it to terminate.
  82. Prints the command to stdout and redirects its output to /dev/null. """
  83. with open('/dev/null', 'w') as devnull:
  84. check_call(command.split(), stdout=devnull, stderr=devnull)
  85. def gradle(*tasks):
  86. """ Runs given gradle tasks """
  87. if tasks:
  88. run_command('./gradlew {}'.format(" ".join(tasks)))
  89. def adb(command):
  90. """ Runs adb command - arguments are given as single string"""
  91. run_command('adb {}'.format(command))
  92. def install_apks(abi):
  93. """ Installs comparison app and test apks """
  94. print("Installing comparison app...")
  95. gradle(':samples:comparison:assembleDebug',
  96. ':samples:comparison:assembleDebugAndroidTest')
  97. adb('uninstall com.facebook.samples.comparison')
  98. adb('uninstall com.facebook.samples.comparison.test')
  99. cmd = ('install -r samples/comparison/build/outputs/apk/comparison-'
  100. '{}-debug.apk'.format(abi))
  101. adb(cmd)
  102. adb('install -r samples/comparison/build/outputs/apk/'
  103. 'comparison-debug-androidTest-unaligned.apk')
  104. class ComparisonTest:
  105. """ Comparison test case """
  106. def __init__(
  107. self,
  108. method_name,
  109. class_name='com.facebook.samples.comparison.test.ScrollTest',
  110. test_package='com.facebook.samples.comparison.test',
  111. test_runner='android.test.InstrumentationTestRunner'):
  112. self.method_name = method_name
  113. self.class_name = class_name
  114. self.test_package = test_package
  115. self.test_runner = test_runner
  116. def __call__(self):
  117. """ Executes test case and captures logcat output """
  118. adb('logcat -c')
  119. with tempfile.TemporaryFile() as logcat_file:
  120. logcat_reader = start_subprocess(
  121. 'adb logcat',
  122. stdout=logcat_file)
  123. adb('shell am instrument -w -e class {}#{} {}/{}'.format(
  124. self.class_name,
  125. self.method_name,
  126. self.test_package,
  127. self.test_runner))
  128. logcat_reader.terminate()
  129. logcat_reader.wait()
  130. logcat_file.seek(0)
  131. self.logcat = logcat_file.readlines()
  132. def get_float_from_logs(regex, logs):
  133. pattern = re.compile(regex)
  134. return [float(match.group(1)) for match in map(pattern.search, logs) if match]
  135. def get_int_from_logs(regex, logs):
  136. pattern = re.compile(regex)
  137. return [int(match.group(1)) for match in map(pattern.search, logs) if match]
  138. def get_stats(logs):
  139. pattern = re.compile("""]: loaded after (\d+) ms""")
  140. success_wait_times = [
  141. int(match.group(1)) for match in map(pattern.search, logs) if match]
  142. pattern = re.compile("""]: failed after (\d+) ms""")
  143. failure_wait_times = [
  144. int(match.group(1)) for match in map(pattern.search, logs) if match]
  145. pattern = re.compile("""]: cancelled after (\d+) ms""")
  146. cancellation_wait_times = [
  147. int(match.group(1)) for match in map(pattern.search, logs) if match]
  148. pattern = re.compile("""\s+(\d+.\d+) MB Java""")
  149. java_heap_sizes = [
  150. float(match.group(1)) for match in map(pattern.search, logs) if match]
  151. pattern = re.compile("""\s+(\d+.\d+) MB native""")
  152. native_heap_sizes = [
  153. float(match.group(1)) for match in map(pattern.search, logs) if match]
  154. pattern = re.compile("""Skipped (\d+) frames! The application may be""")
  155. skipped_frames = [
  156. int(match.group(1)) for match in map(pattern.search, logs) if match]
  157. return Stats(
  158. success_wait_times,
  159. failure_wait_times,
  160. cancellation_wait_times,
  161. java_heap_sizes,
  162. native_heap_sizes,
  163. skipped_frames)
  164. def print_stats(stats):
  165. successes = len(stats.success_wait_times)
  166. cancellations = len(stats.cancellation_wait_times)
  167. failures = len(stats.failure_wait_times)
  168. total_count = successes + cancellations + failures
  169. if total_count == 0:
  170. print("Unable to read logs.")
  171. return
  172. total_wait_time = (
  173. sum(stats.success_wait_times) +
  174. sum(stats.cancellation_wait_times) +
  175. sum(stats.failure_wait_times))
  176. avg_wait_time = float(total_wait_time) / total_count
  177. max_java_heap = max(stats.java_heap_sizes)
  178. max_native_heap = max(stats.native_heap_sizes)
  179. total_skipped_frames = sum(stats.skipped_frames)
  180. print("Average wait time = {0:.1f}".format(avg_wait_time))
  181. print("Successful requests = {}".format(successes))
  182. print("Failures = {}".format(failures))
  183. print("Cancellations = {}".format(cancellations))
  184. print("Max java heap = {0:.1f}".format(max_java_heap))
  185. print("Max native heap = {0:.1f}".format(max_native_heap))
  186. print("Total skipped frames = {}".format(total_skipped_frames))
  187. def get_test_name(option_name, source_name):
  188. return TEST_PATTERN.format(
  189. ''.join(word.capitalize() for word in option_name.split('-')), source_name.capitalize())
  190. def valid_scenario(scenario_name, source_name):
  191. return source_name != 'local' or (scenario_name != 'volley' and scenario_name != 'drawee-volley')
  192. def list_producers():
  193. sdir = os.path.dirname(os.path.abspath(__file__))
  194. producer_path = '%s/imagepipeline/src/main/java/com/facebook/imagepipeline/producers/*Producer.java' % sdir
  195. files = glob.glob(producer_path)
  196. return [f.split('.')[0].split('/')[-1] for f in files]
  197. def print_fresco_perf_line(margin, name, times):
  198. length = len(times)
  199. if length == 0:
  200. return
  201. print("%s: %d requests, avg %d" % (name.rjust(margin), length, float(sum(times)) / length))
  202. def print_fresco_perf(logs):
  203. producers = list_producers()
  204. margin = max([len(p) for p in producers])
  205. requests = get_int_from_logs(""".*RequestLoggingListener.*onRequestSuccess.*elapsedTime:\s(\d+).*""", logs)
  206. print_fresco_perf_line(margin, 'Total', requests)
  207. for producer in producers:
  208. queue = get_int_from_logs(".*onProducerFinishWithSuccess.*producer:\s%s.*queueTime=(\d+).*" % producer, logs)
  209. print_fresco_perf_line(margin, '%s queue' % producer, queue)
  210. times = get_int_from_logs(".*onProducerFinishWithSuccess.*producer:\s%s.*elapsedTime:\s(\d+).*" % producer, logs)
  211. print_fresco_perf_line(margin, producer, times)
  212. def main():
  213. args = parse_args()
  214. scenarios = []
  215. sources = []
  216. if args.scenarios:
  217. scenarios = args.scenarios
  218. else:
  219. scenarios = TESTS
  220. if args.sources:
  221. sources = args.sources
  222. else:
  223. sources = TEST_SOURCES
  224. install_apks(args.cpu)
  225. for source_name in sources:
  226. for scenario_name in scenarios:
  227. if valid_scenario(scenario_name, source_name):
  228. print()
  229. print('Testing {} {}'.format(scenario_name, source_name))
  230. print(get_test_name(scenario_name, source_name))
  231. test = ComparisonTest(get_test_name(scenario_name, source_name))
  232. test()
  233. stats = get_stats(test.logcat)
  234. print_stats(stats)
  235. if scenario_name[:6] == 'fresco':
  236. print()
  237. print_fresco_perf(test.logcat)
  238. if __name__ == "__main__":
  239. main()