code_size_compare.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. class CodeSizeComparison:
  29. """Compare code size between two Git revisions."""
  30. def __init__(self, old_revision, new_revision, result_dir):
  31. """
  32. old_revision: revision to compare against
  33. new_revision:
  34. result_dir: directory for comparision result
  35. """
  36. self.repo_path = "."
  37. self.result_dir = os.path.abspath(result_dir)
  38. os.makedirs(self.result_dir, exist_ok=True)
  39. self.csv_dir = os.path.abspath("code_size_records/")
  40. os.makedirs(self.csv_dir, exist_ok=True)
  41. self.old_rev = old_revision
  42. self.new_rev = new_revision
  43. self.git_command = "git"
  44. self.make_command = "make"
  45. @staticmethod
  46. def check_repo_path():
  47. if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
  48. raise Exception("Must be run from Mbed TLS root")
  49. @staticmethod
  50. def validate_revision(revision):
  51. result = subprocess.check_output(["git", "rev-parse", "--verify",
  52. revision + "^{commit}"], shell=False)
  53. return result
  54. def _create_git_worktree(self, revision):
  55. """Make a separate worktree for revision.
  56. Do not modify the current worktree."""
  57. if revision == "current":
  58. print("Using current work directory.")
  59. git_worktree_path = self.repo_path
  60. else:
  61. print("Creating git worktree for", revision)
  62. git_worktree_path = os.path.join(self.repo_path, "temp-" + revision)
  63. subprocess.check_output(
  64. [self.git_command, "worktree", "add", "--detach",
  65. git_worktree_path, revision], cwd=self.repo_path,
  66. stderr=subprocess.STDOUT
  67. )
  68. return git_worktree_path
  69. def _build_libraries(self, git_worktree_path):
  70. """Build libraries in the specified worktree."""
  71. my_environment = os.environ.copy()
  72. subprocess.check_output(
  73. [self.make_command, "-j", "lib"], env=my_environment,
  74. cwd=git_worktree_path, stderr=subprocess.STDOUT,
  75. )
  76. def _gen_code_size_csv(self, revision, git_worktree_path):
  77. """Generate code size csv file."""
  78. csv_fname = revision + ".csv"
  79. if revision == "current":
  80. print("Measuring code size in current work directory.")
  81. else:
  82. print("Measuring code size for", revision)
  83. result = subprocess.check_output(
  84. ["size library/*.o"], cwd=git_worktree_path, shell=True
  85. )
  86. size_text = result.decode()
  87. csv_file = open(os.path.join(self.csv_dir, csv_fname), "w")
  88. for line in size_text.splitlines()[1:]:
  89. data = line.split()
  90. csv_file.write("{}, {}\n".format(data[5], data[3]))
  91. def _remove_worktree(self, git_worktree_path):
  92. """Remove temporary worktree."""
  93. if git_worktree_path != self.repo_path:
  94. print("Removing temporary worktree", git_worktree_path)
  95. subprocess.check_output(
  96. [self.git_command, "worktree", "remove", "--force",
  97. git_worktree_path], cwd=self.repo_path,
  98. stderr=subprocess.STDOUT
  99. )
  100. def _get_code_size_for_rev(self, revision):
  101. """Generate code size csv file for the specified git revision."""
  102. # Check if the corresponding record exists
  103. csv_fname = revision + ".csv"
  104. if (revision != "current") and \
  105. os.path.exists(os.path.join(self.csv_dir, csv_fname)):
  106. print("Code size csv file for", revision, "already exists.")
  107. else:
  108. git_worktree_path = self._create_git_worktree(revision)
  109. self._build_libraries(git_worktree_path)
  110. self._gen_code_size_csv(revision, git_worktree_path)
  111. self._remove_worktree(git_worktree_path)
  112. def compare_code_size(self):
  113. """Generate results of the size changes between two revisions,
  114. old and new. Measured code size results of these two revisions
  115. must be available."""
  116. old_file = open(os.path.join(self.csv_dir, self.old_rev + ".csv"), "r")
  117. new_file = open(os.path.join(self.csv_dir, self.new_rev + ".csv"), "r")
  118. res_file = open(os.path.join(self.result_dir, "compare-" + self.old_rev
  119. + "-" + self.new_rev + ".csv"), "w")
  120. res_file.write("file_name, this_size, old_size, change, change %\n")
  121. print("Generating comparision results.")
  122. old_ds = {}
  123. for line in old_file.readlines()[1:]:
  124. cols = line.split(", ")
  125. fname = cols[0]
  126. size = int(cols[1])
  127. if size != 0:
  128. old_ds[fname] = size
  129. new_ds = {}
  130. for line in new_file.readlines()[1:]:
  131. cols = line.split(", ")
  132. fname = cols[0]
  133. size = int(cols[1])
  134. new_ds[fname] = size
  135. for fname in new_ds:
  136. this_size = new_ds[fname]
  137. if fname in old_ds:
  138. old_size = old_ds[fname]
  139. change = this_size - old_size
  140. change_pct = change / old_size
  141. res_file.write("{}, {}, {}, {}, {:.2%}\n".format(fname, \
  142. this_size, old_size, change, float(change_pct)))
  143. else:
  144. res_file.write("{}, {}\n".format(fname, this_size))
  145. return 0
  146. def get_comparision_results(self):
  147. """Compare size of library/*.o between self.old_rev and self.new_rev,
  148. and generate the result file."""
  149. self.check_repo_path()
  150. self._get_code_size_for_rev(self.old_rev)
  151. self._get_code_size_for_rev(self.new_rev)
  152. return self.compare_code_size()
  153. def main():
  154. parser = argparse.ArgumentParser(
  155. description=(
  156. """This script is for comparing the size of the library files
  157. from two different Git revisions within an Mbed TLS repository.
  158. The results of the comparison is formatted as csv, and stored at
  159. a configurable location.
  160. Note: must be run from Mbed TLS root."""
  161. )
  162. )
  163. parser.add_argument(
  164. "-r", "--result-dir", type=str, default="comparison",
  165. help="directory where comparison result is stored, \
  166. default is comparison",
  167. )
  168. parser.add_argument(
  169. "-o", "--old-rev", type=str, help="old revision for comparison.",
  170. required=True,
  171. )
  172. parser.add_argument(
  173. "-n", "--new-rev", type=str, default=None,
  174. help="new revision for comparison, default is the current work \
  175. directory, including uncommited changes."
  176. )
  177. comp_args = parser.parse_args()
  178. if os.path.isfile(comp_args.result_dir):
  179. print("Error: {} is not a directory".format(comp_args.result_dir))
  180. parser.exit()
  181. validate_res = CodeSizeComparison.validate_revision(comp_args.old_rev)
  182. old_revision = validate_res.decode().replace("\n", "")
  183. if comp_args.new_rev is not None:
  184. validate_res = CodeSizeComparison.validate_revision(comp_args.new_rev)
  185. new_revision = validate_res.decode().replace("\n", "")
  186. else:
  187. new_revision = "current"
  188. result_dir = comp_args.result_dir
  189. size_compare = CodeSizeComparison(old_revision, new_revision, result_dir)
  190. return_code = size_compare.get_comparision_results()
  191. sys.exit(return_code)
  192. if __name__ == "__main__":
  193. main()