Skip to content

Commit af7db19

Browse files
Michael0x2agvanrossum
authored andcommitted
Add Michael's test scripts for incremental to misc folder (#2117)
1 parent b622426 commit af7db19

File tree

4 files changed

+504
-0
lines changed

4 files changed

+504
-0
lines changed

misc/analyze_cache.py

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
#!/usr/bin/env python
2+
3+
from typing import Any, Dict, Generator, Iterable, List, Optional
4+
from collections import Counter
5+
6+
import os
7+
import os.path
8+
import json
9+
10+
ROOT = ".mypy_cache/3.5"
11+
12+
JsonDict = Dict[str, Any]
13+
14+
class CacheData:
15+
def __init__(self, filename: str, data_json: JsonDict, meta_json: JsonDict,
16+
data_size: int, meta_size: int) -> None:
17+
self.filename = filename
18+
self.data = data_json
19+
self.meta = meta_json
20+
self.data_size = data_size
21+
self.meta_size = meta_size
22+
23+
@property
24+
def total_size(self):
25+
return self.data_size + self.meta_size
26+
27+
28+
def extract_classes(chunks: Iterable[CacheData]) -> Iterable[JsonDict]:
29+
def extract(chunks: Iterable[JsonDict]) -> Iterable[JsonDict]:
30+
for chunk in chunks:
31+
if isinstance(chunk, dict):
32+
yield chunk
33+
yield from extract(chunk.values())
34+
elif isinstance(chunk, list):
35+
yield from extract(chunk)
36+
yield from extract([chunk.data for chunk in chunks])
37+
38+
39+
def load_json(data_path: str, meta_path: str) -> CacheData:
40+
with open(data_path, 'r') as ds:
41+
data_json = json.load(ds)
42+
43+
with open(meta_path, 'r') as ms:
44+
meta_json = json.load(ms)
45+
46+
data_size = os.path.getsize(data_path)
47+
meta_size = os.path.getsize(meta_path)
48+
49+
return CacheData(data_path.replace(".data.json", ".*.json"),
50+
data_json, meta_json, data_size, meta_size)
51+
52+
53+
def get_files(root: str) -> Iterable[CacheData]:
54+
for (dirpath, dirnames, filenames) in os.walk(root):
55+
for filename in filenames:
56+
if filename.endswith(".data.json"):
57+
meta_filename = filename.replace(".data.json", ".meta.json")
58+
yield load_json(
59+
os.path.join(dirpath, filename),
60+
os.path.join(dirpath, meta_filename))
61+
62+
63+
def pluck(name: str, chunks: Iterable[JsonDict]) -> Iterable[JsonDict]:
64+
return (chunk for chunk in chunks if chunk['.class'] == name)
65+
66+
67+
def report_counter(counter: Counter, amount: Optional[int] = None) -> None:
68+
for name, count in counter.most_common(amount):
69+
print(' {: <8} {}'.format(count, name))
70+
print()
71+
72+
73+
def report_most_common(chunks: List[JsonDict], amount: Optional[int] = None) -> None:
74+
report_counter(Counter(str(chunk) for chunk in chunks), amount)
75+
76+
77+
def compress(chunk: JsonDict) -> JsonDict:
78+
cache = {} # type: Dict[int, JsonDict]
79+
counter = 0
80+
def helper(chunk: Any) -> Any:
81+
nonlocal counter
82+
if not isinstance(chunk, dict):
83+
return chunk
84+
85+
if len(chunk) <= 2:
86+
return chunk
87+
id = hash(str(chunk))
88+
89+
if id in cache:
90+
return cache[id]
91+
else:
92+
cache[id] = {'.id': counter}
93+
chunk['.cache_id'] = counter
94+
counter += 1
95+
96+
for name in sorted(chunk.keys()):
97+
value = chunk[name]
98+
if isinstance(value, list):
99+
chunk[name] = [helper(child) for child in value]
100+
elif isinstance(value, dict):
101+
chunk[name] = helper(value)
102+
103+
return chunk
104+
out = helper(chunk)
105+
return out
106+
107+
def decompress(chunk: JsonDict) -> JsonDict:
108+
cache = {} # type: Dict[int, JsonDict]
109+
def helper(chunk: Any) -> Any:
110+
if not isinstance(chunk, dict):
111+
return chunk
112+
if '.id' in chunk:
113+
return cache[chunk['.id']]
114+
115+
counter = None
116+
if '.cache_id' in chunk:
117+
counter = chunk['.cache_id']
118+
del chunk['.cache_id']
119+
120+
for name in sorted(chunk.keys()):
121+
value = chunk[name]
122+
if isinstance(value, list):
123+
chunk[name] = [helper(child) for child in value]
124+
elif isinstance(value, dict):
125+
chunk[name] = helper(value)
126+
127+
if counter is not None:
128+
cache[counter] = chunk
129+
130+
return chunk
131+
return helper(chunk)
132+
133+
134+
135+
136+
def main() -> None:
137+
json_chunks = list(get_files(ROOT))
138+
class_chunks = list(extract_classes(json_chunks))
139+
140+
total_size = sum(chunk.total_size for chunk in json_chunks)
141+
print("Total cache size: {:.3f} megabytes".format(total_size / (1024 * 1024)))
142+
print()
143+
144+
class_name_counter = Counter(chunk[".class"] for chunk in class_chunks)
145+
print("Most commonly used classes:")
146+
report_counter(class_name_counter)
147+
148+
print("Most common literal chunks:")
149+
report_most_common(class_chunks, 15)
150+
151+
build = None
152+
for chunk in json_chunks:
153+
if 'build.*.json' in chunk.filename:
154+
build = chunk
155+
break
156+
original = json.dumps(build.data, sort_keys=True)
157+
print("Size of build.data.json, in kilobytes: {:.3f}".format(len(original) / 1024))
158+
159+
build.data = compress(build.data)
160+
compressed = json.dumps(build.data, sort_keys=True)
161+
print("Size of compressed build.data.json, in kilobytes: {:.3f}".format(len(compressed) / 1024))
162+
163+
build.data = decompress(build.data)
164+
decompressed = json.dumps(build.data, sort_keys=True)
165+
print("Size of decompressed build.data.json, in kilobytes: {:.3f}".format(len(decompressed) / 1024))
166+
167+
print("Lossless conversion back", original == decompressed)
168+
169+
170+
'''var_chunks = list(pluck("Var", class_chunks))
171+
report_most_common(var_chunks, 20)
172+
print()
173+
174+
#for var in var_chunks:
175+
# if var['fullname'] == 'self' and not (isinstance(var['type'], dict) and var['type']['.class'] == 'AnyType'):
176+
# print(var)
177+
#argument_chunks = list(pluck("Argument", class_chunks))
178+
179+
symbol_table_node_chunks = list(pluck("SymbolTableNode", class_chunks))
180+
report_most_common(symbol_table_node_chunks, 20)
181+
182+
print()
183+
print("Most common")
184+
report_most_common(class_chunks, 20)
185+
print()'''
186+
187+
188+
if __name__ == '__main__':
189+
main()

misc/perf_checker.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#!/usr/bin/env python3
2+
3+
from typing import Callable, List, Tuple
4+
5+
import os
6+
import shutil
7+
import statistics
8+
import subprocess
9+
import textwrap
10+
import time
11+
12+
13+
class Command:
14+
def __init__(self, setup: Callable[[], None], command: Callable[[], None]) -> None:
15+
self.setup = setup
16+
self.command = command
17+
18+
19+
def print_offset(text: str, indent_length: int = 4) -> None:
20+
print()
21+
print(textwrap.indent(text, ' ' * indent_length))
22+
print()
23+
24+
25+
def delete_folder(folder_path: str) -> None:
26+
if os.path.exists(folder_path):
27+
shutil.rmtree(folder_path)
28+
29+
30+
def execute(command: List[str]) -> None:
31+
proc = subprocess.Popen(
32+
' '.join(command),
33+
stderr=subprocess.PIPE,
34+
stdout=subprocess.PIPE,
35+
shell=True)
36+
stdout_bytes, stderr_bytes = proc.communicate() # type: Tuple[bytes, bytes]
37+
stdout, stderr = stdout_bytes.decode('utf-8'), stderr_bytes.decode('utf-8')
38+
if proc.returncode != 0:
39+
print('EXECUTED COMMAND:', repr(command))
40+
print('RETURN CODE:', proc.returncode)
41+
print()
42+
print('STDOUT:')
43+
print_offset(stdout)
44+
print('STDERR:')
45+
print_offset(stderr)
46+
raise RuntimeError('Unexpected error from external tool.')
47+
48+
49+
def trial(num_trials: int, command: Command) -> List[float]:
50+
trials = []
51+
for i in range(num_trials):
52+
command.setup()
53+
start = time.time()
54+
command.command()
55+
delta = time.time() - start
56+
trials.append(delta)
57+
return trials
58+
59+
60+
def report(name: str, times: List[float]) -> None:
61+
print("{}:".format(name))
62+
print(" Times: {}".format(times))
63+
print(" Mean: {}".format(statistics.mean(times)))
64+
print(" Stdev: {}".format(statistics.stdev(times)))
65+
print()
66+
67+
68+
def main() -> None:
69+
trials = 3
70+
71+
print("Testing baseline")
72+
baseline = trial(trials, Command(
73+
lambda: None,
74+
lambda: execute(["python3", "-m", "mypy", "mypy"])))
75+
report("Baseline", baseline)
76+
77+
print("Testing cold cache")
78+
cold_cache = trial(trials, Command(
79+
lambda: delete_folder(".mypy_cache"),
80+
lambda: execute(["python3", "-m", "mypy", "-i", "mypy"])))
81+
report("Cold cache", cold_cache)
82+
83+
print("Testing warm cache")
84+
execute(["python3", "-m", "mypy", "-i", "mypy"])
85+
warm_cache = trial(trials, Command(
86+
lambda: None,
87+
lambda: execute(["python3", "-m", "mypy", "-i", "mypy"])))
88+
report("Warm cache", warm_cache)
89+
90+
91+
if __name__ == '__main__':
92+
main()
93+

misc/test_case_to_actual.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
from typing import Iterator, List
2+
import sys
3+
import os
4+
import os.path
5+
6+
7+
class Chunk:
8+
def __init__(self, header_type: str, args: str) -> None:
9+
self.header_type = header_type
10+
self.args = args
11+
self.lines = [] # type: List[str]
12+
13+
14+
def is_header(line: str) -> bool:
15+
return line.startswith('[') and line.endswith(']')
16+
17+
18+
def normalize(lines: Iterator[str]) -> Iterator[str]:
19+
return (line.rstrip() for line in lines)
20+
21+
22+
def produce_chunks(lines: Iterator[str]) -> Iterator[Chunk]:
23+
current_chunk = None # type: Chunk
24+
for line in normalize(lines):
25+
if is_header(line):
26+
if current_chunk is not None:
27+
yield current_chunk
28+
parts = line[1:-1].split(' ', 1)
29+
args = parts[1] if len(parts) > 1 else ''
30+
current_chunk = Chunk(parts[0], args)
31+
else:
32+
current_chunk.lines.append(line)
33+
if current_chunk is not None:
34+
yield current_chunk
35+
36+
37+
def write_out(filename: str, lines: List[str]) -> None:
38+
os.makedirs(os.path.dirname(filename), exist_ok=True)
39+
with open(filename, 'w') as stream:
40+
stream.write('\n'.join(lines))
41+
42+
43+
def write_tree(root: str, chunks: Iterator[Chunk]) -> None:
44+
init = next(chunks)
45+
assert init.header_type == 'case'
46+
47+
root = os.path.join(root, init.args)
48+
write_out(os.path.join(root, 'main.py'), init.lines)
49+
50+
for chunk in chunks:
51+
if chunk.header_type == 'file' and chunk.args.endswith('.py'):
52+
write_out(os.path.join(root, chunk.args), chunk.lines)
53+
54+
55+
def help() -> None:
56+
print("Usage: python misc/test_case_to_actual.py test_file.txt root_path")
57+
58+
59+
def main() -> None:
60+
if len(sys.argv) != 3:
61+
help()
62+
return
63+
64+
test_file_path, root_path = sys.argv[1], sys.argv[2]
65+
with open(test_file_path, 'r') as stream:
66+
chunks = produce_chunks(iter(stream))
67+
write_tree(root_path, chunks)
68+
69+
70+
if __name__ == '__main__':
71+
main()

0 commit comments

Comments
 (0)