code_size_compare.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. #!/usr/bin/env python3
  2. """
  3. Purpose
  4. This script is for comparing the size of the library files from two
  5. different Git revisions within an Mbed TLS repository.
  6. The results of the comparison is formatted as csv and stored at a
  7. configurable location.
  8. Note: must be run from Mbed TLS root.
  9. """
  10. # Copyright The Mbed TLS Contributors
  11. # SPDX-License-Identifier: Apache-2.0
  12. #
  13. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  14. # not use this file except in compliance with the License.
  15. # You may obtain a copy of the License at
  16. #
  17. # http://www.apache.org/licenses/LICENSE-2.0
  18. #
  19. # Unless required by applicable law or agreed to in writing, software
  20. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. # See the License for the specific language governing permissions and
  23. # limitations under the License.
  24. import argparse
  25. import os
  26. import subprocess
  27. import sys
  28. from mbedtls_dev import build_tree
  29. class CodeSizeComparison:
  30. """Compare code size between two Git revisions."""
  31. def __init__(self, old_revision, new_revision, result_dir):
  32. """
  33. old_revision: revision to compare against
  34. new_revision:
  35. result_dir: directory for comparison result
  36. """
  37. self.repo_path = "."
  38. self.result_dir = os.path.abspath(result_dir)
  39. os.makedirs(self.result_dir, exist_ok=True)
  40. self.csv_dir = os.path.abspath("code_size_records/")
  41. os.makedirs(self.csv_dir, exist_ok=True)
  42. self.old_rev = old_revision
  43. self.new_rev = new_revision
  44. self.git_command = "git"
  45. self.make_command = "make"
  46. @staticmethod
  47. def validate_revision(revision):
  48. result = subprocess.check_output(["git", "rev-parse", "--verify",
  49. revision + "^{commit}"], shell=False)
  50. return result
  51. def _create_git_worktree(self, revision):
  52. """Make a separate worktree for revision.
  53. Do not modify the current worktree."""
  54. if revision == "current":
  55. print("Using current work directory.")
  56. git_worktree_path = self.repo_path
  57. else:
  58. print("Creating git worktree for", revision)
  59. git_worktree_path = os.path.join(self.repo_path, "temp-" + revision)
  60. subprocess.check_output(
  61. [self.git_command, "worktree", "add", "--detach",
  62. git_worktree_path, revision], cwd=self.repo_path,
  63. stderr=subprocess.STDOUT
  64. )
  65. return git_worktree_path
  66. def _build_libraries(self, git_worktree_path):
  67. """Build libraries in the specified worktree."""
  68. my_environment = os.environ.copy()
  69. subprocess.check_output(
  70. [self.make_command, "-j", "lib"], env=my_environment,
  71. cwd=git_worktree_path, stderr=subprocess.STDOUT,
  72. )
  73. def _gen_code_size_csv(self, revision, git_worktree_path):
  74. """Generate code size csv file."""
  75. csv_fname = revision + ".csv"
  76. if revision == "current":
  77. print("Measuring code size in current work directory.")
  78. else:
  79. print("Measuring code size for", revision)
  80. result = subprocess.check_output(
  81. ["size library/*.o"], cwd=git_worktree_path, shell=True
  82. )
  83. size_text = result.decode()
  84. csv_file = open(os.path.join(self.csv_dir, csv_fname), "w")
  85. for line in size_text.splitlines()[1:]:
  86. data = line.split()
  87. csv_file.write("{}, {}\n".format(data[5], data[3]))
  88. def _remove_worktree(self, git_worktree_path):
  89. """Remove temporary worktree."""
  90. if git_worktree_path != self.repo_path:
  91. print("Removing temporary worktree", git_worktree_path)
  92. subprocess.check_output(
  93. [self.git_command, "worktree", "remove", "--force",
  94. git_worktree_path], cwd=self.repo_path,
  95. stderr=subprocess.STDOUT
  96. )
  97. def _get_code_size_for_rev(self, revision):
  98. """Generate code size csv file for the specified git revision."""
  99. # Check if the corresponding record exists
  100. csv_fname = revision + ".csv"
  101. if (revision != "current") and \
  102. os.path.exists(os.path.join(self.csv_dir, csv_fname)):
  103. print("Code size csv file for", revision, "already exists.")
  104. else:
  105. git_worktree_path = self._create_git_worktree(revision)
  106. self._build_libraries(git_worktree_path)
  107. self._gen_code_size_csv(revision, git_worktree_path)
  108. self._remove_worktree(git_worktree_path)
  109. def compare_code_size(self):
  110. """Generate results of the size changes between two revisions,
  111. old and new. Measured code size results of these two revisions
  112. must be available."""
  113. old_file = open(os.path.join(self.csv_dir, self.old_rev + ".csv"), "r")
  114. new_file = open(os.path.join(self.csv_dir, self.new_rev + ".csv"), "r")
  115. res_file = open(os.path.join(self.result_dir, "compare-" + self.old_rev
  116. + "-" + self.new_rev + ".csv"), "w")
  117. res_file.write("file_name, this_size, old_size, change, change %\n")
  118. print("Generating comparison results.")
  119. old_ds = {}
  120. for line in old_file.readlines()[1:]:
  121. cols = line.split(", ")
  122. fname = cols[0]
  123. size = int(cols[1])
  124. if size != 0:
  125. old_ds[fname] = size
  126. new_ds = {}
  127. for line in new_file.readlines()[1:]:
  128. cols = line.split(", ")
  129. fname = cols[0]
  130. size = int(cols[1])
  131. new_ds[fname] = size
  132. for fname in new_ds:
  133. this_size = new_ds[fname]
  134. if fname in old_ds:
  135. old_size = old_ds[fname]
  136. change = this_size - old_size
  137. change_pct = change / old_size
  138. res_file.write("{}, {}, {}, {}, {:.2%}\n".format(fname, \
  139. this_size, old_size, change, float(change_pct)))
  140. else:
  141. res_file.write("{}, {}\n".format(fname, this_size))
  142. return 0
  143. def get_comparision_results(self):
  144. """Compare size of library/*.o between self.old_rev and self.new_rev,
  145. and generate the result file."""
  146. build_tree.check_repo_path()
  147. self._get_code_size_for_rev(self.old_rev)
  148. self._get_code_size_for_rev(self.new_rev)
  149. return self.compare_code_size()
  150. def main():
  151. parser = argparse.ArgumentParser(
  152. description=(
  153. """This script is for comparing the size of the library files
  154. from two different Git revisions within an Mbed TLS repository.
  155. The results of the comparison is formatted as csv, and stored at
  156. a configurable location.
  157. Note: must be run from Mbed TLS root."""
  158. )
  159. )
  160. parser.add_argument(
  161. "-r", "--result-dir", type=str, default="comparison",
  162. help="directory where comparison result is stored, \
  163. default is comparison",
  164. )
  165. parser.add_argument(
  166. "-o", "--old-rev", type=str, help="old revision for comparison.",
  167. required=True,
  168. )
  169. parser.add_argument(
  170. "-n", "--new-rev", type=str, default=None,
  171. help="new revision for comparison, default is the current work \
  172. directory, including uncommitted changes."
  173. )
  174. comp_args = parser.parse_args()
  175. if os.path.isfile(comp_args.result_dir):
  176. print("Error: {} is not a directory".format(comp_args.result_dir))
  177. parser.exit()
  178. validate_res = CodeSizeComparison.validate_revision(comp_args.old_rev)
  179. old_revision = validate_res.decode().replace("\n", "")
  180. if comp_args.new_rev is not None:
  181. validate_res = CodeSizeComparison.validate_revision(comp_args.new_rev)
  182. new_revision = validate_res.decode().replace("\n", "")
  183. else:
  184. new_revision = "current"
  185. result_dir = comp_args.result_dir
  186. size_compare = CodeSizeComparison(old_revision, new_revision, result_dir)
  187. return_code = size_compare.get_comparision_results()
  188. sys.exit(return_code)
  189. if __name__ == "__main__":
  190. main()