Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/tools/emprofile.py
6162 views
1
#!/usr/bin/env python3
2
# Copyright 2016 The Emscripten Authors. All rights reserved.
3
# Emscripten is available under two separate licenses, the MIT license and the
4
# University of Illinois/NCSA Open Source License. Both these licenses can be
5
# found in the LICENSE file.
6
7
import json
8
import os
9
import shutil
10
import sys
11
import tempfile
12
import time
13
from pathlib import Path
14
15
profiler_logs_path = os.path.join(tempfile.gettempdir(), 'emscripten_toolchain_profiler_logs')
16
17
18
# Deletes all previously captured log files to make room for a new clean run.
19
def delete_profiler_logs():
20
if os.path.exists(profiler_logs_path):
21
shutil.rmtree(profiler_logs_path)
22
23
24
def list_files_in_directory(d):
25
files = []
26
if os.path.exists(d):
27
for i in os.listdir(d):
28
f = os.path.join(d, i)
29
if os.path.isfile(f):
30
files.append(f)
31
return files
32
33
34
def create_profiling_graph(outfile):
35
log_files = [f for f in list_files_in_directory(profiler_logs_path) if 'toolchain_profiler.pid_' in f]
36
37
all_results = []
38
if log_files:
39
print(f'Processing {len(log_files)} profile log files in {profiler_logs_path}...')
40
for f in log_files:
41
print(f'Processing: {f}')
42
json_data = Path(f).read_text()
43
if len(json_data.strip()) == 0:
44
continue
45
lines = json_data.split('\n')
46
lines = [x for x in lines if x not in {'[', ']', ','} and len(x.strip())]
47
lines = [(x + ',') if not x.endswith(',') else x for x in lines]
48
lines[-1] = lines[-1][:-1]
49
json_data = '[' + '\n'.join(lines) + ']'
50
try:
51
all_results += json.loads(json_data)
52
except json.JSONDecodeError as e:
53
print(str(e), file=sys.stderr)
54
print('Failed to parse JSON file "' + f + '"!', file=sys.stderr)
55
return 1
56
if len(all_results) == 0:
57
print(f'No profiler logs were found in path: ${profiler_logs_path}.\nTry setting the environment variable EMPROFILE=1 and run some emcc commands, then re-run "emprofile.py --graph".', file=sys.stderr)
58
return 1
59
60
all_results.sort(key=lambda x: x['time'])
61
62
emprofile_json_data = json.dumps(all_results, indent=2)
63
64
html_file = outfile + '.html'
65
html_contents = Path(os.path.dirname(os.path.realpath(__file__)), 'toolchain_profiler.results_template.html').read_text().replace('{{{ emprofile_json_data }}}', emprofile_json_data)
66
Path(html_file).write_text(html_contents)
67
print(f'Wrote "{html_file}"')
68
return 0
69
70
71
def main(args):
72
if '--help' in args:
73
print('''\
74
Usage:
75
emprofile.py --clear (or -c)
76
Deletes all previously recorded profiling log files.
77
Use this to abort/drop any previously collected
78
profiling data for a new profiling run.
79
80
emprofile.py [--no-clear]
81
Draws a graph from all recorded profiling log files,
82
and deletes the recorded profiling files, unless
83
--no-clear is also passed.
84
85
Optional parameters:
86
87
--outfile=x.html (or -o=x.html)
88
Specifies the name of the results file to generate.
89
''')
90
return 0
91
92
if '--reset' in args or '--clear' in args or '-c' in args:
93
delete_profiler_logs()
94
return 0
95
else:
96
outfile = 'toolchain_profiler.results_' + time.strftime('%Y%m%d_%H%M')
97
for i, arg in enumerate(args):
98
if arg.startswith(('--outfile=', '-o=')):
99
outfile = arg.split('=', 1)[1].strip().replace('.html', '')
100
elif arg == '-o':
101
outfile = args[i + 1].strip().replace('.html', '')
102
if create_profiling_graph(outfile):
103
return 1
104
if '--no-clear' not in args:
105
delete_profiler_logs()
106
107
return 0
108
109
110
if __name__ == '__main__':
111
sys.exit(main(sys.argv[1:]))
112
113