1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
|
import os
import shutil
import glob
import subprocess
import argparse
import sys
import prettytable
import json
### Setup ###
def clear_mkdir(dir):
if os.path.exists(dir):
shutil.rmtree(dir)
os.makedirs(dir, exist_ok=True)
clear_mkdir('modules')
clear_mkdir('targets')
clear_mkdir('targets/generated')
target_choices = [
'spirv', # SPIRV directly
'spirv-glsl', # SPIRV through synthesized GLSL
'dxil', # DXIL with HLSL and DXC
'dxil-embedded' # DXIL with precompiled modules
]
parser = argparse.ArgumentParser()
parser.add_argument('--target', type=str, default='spirv', choices=target_choices)
parser.add_argument('--samples', type=int, default=1)
parser.add_argument('--output', type=str, default='benchmarks.json')
args = parser.parse_args(sys.argv[1:])
slangc = '..\\..\\build\\Release\\bin\\slangc.exe'
target = args.target
samples = args.samples
if target == 'spirv':
target = 'spirv -emit-spirv-directly'
target_ext = 'spirv'
embed = False
elif target == 'spirv-glsl':
target = 'spirv -emit-spirv-via-glsl'
target_ext = 'spirv'
embed = False
elif target == 'dxil-embedded':
target_ext = 'dxil'
embed = True
elif target == 'dxil':
target_ext = 'dxil'
embed = False
print(f'slangc: {slangc}')
print(f'target: {target}')
print(f'samples: {samples}\n')
### Utility ###
def parse(results):
results = results.split('\n')
results = [ r for r in results if r.startswith('[*]') ]
results = [ r.split() for r in results ]
profile = {}
for r in results:
profile[r[1]] = float(r[-1][:-2])
return profile
timings = {}
def run(command, key):
profile = {}
for i in range(samples):
try:
results = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True).decode('utf-8')
except subprocess.CalledProcessError as exc:
print(exc.output.decode('utf-8'))
return
# exit(-1)
p = parse(results)
if len(profile) == 0:
profile = p
else:
for k, v in p.items():
profile.setdefault(k, 0)
profile[k] += v
for k in profile:
profile[k] /= samples
timings[key] = profile
def compile_cmd(file, output, stage=None, entry=None, emit=False):
cmd = f'{slangc} -report-perf-benchmark {file}'
if stage:
cmd += f' -stage {stage}'
if entry:
cmd += f' -entry {entry}'
else:
cmd += f' -entry {stage}'
if emit:
cmd += f' -target {target_ext}'
output += '.' + target_ext
if target == 'dxil-embedded':
cmd += ' -profile lib_6_6'
elif embed:
cmd += ' -embed-dxil'
cmd += f' -o {output}'
return cmd
### Monolithic compilation ###
hit = 'hit.slang'
cmd = compile_cmd(hit, f'targets/dxr-ch-mono', stage='closesthit', entry='MdlRadianceClosestHitProgram', emit=True)
run(cmd, f'full/{target_ext}/mono/closesthit')
print(f'[I] compiled shadow (monolithic)')
cmd = compile_cmd(hit, f'targets/dxr-ah-mono', stage='anyhit', entry='MdlRadianceAnyHitProgram', emit=True)
run(cmd, f'full/{target_ext}/mono/anyhit')
print(f'[I] compiled shadow (monolithic)')
cmd = compile_cmd(hit, f'targets/dxr-sh-mono', stage='anyhit', entry='MdlShadowAnyHitProgram', emit=True)
run(cmd, f'full/{target_ext}/mono/shadow')
print(f'[I] compiled shadow (monolithic)')
### Module precompilation ###
modules = []
for file in glob.glob(f'*.slang'):
if not file.endswith('hit.slang'):
basename = os.path.basename(file)
run(compile_cmd(file, f'modules/{basename}-module'), 'module/' + file)
print(f'[I] compiled {file}.')
### Module whole compilation ###
cmd = compile_cmd(hit, f'targets/dxr-ch-modules', stage='closesthit', entry='MdlRadianceClosestHitProgram', emit=True)
run(cmd, f'full/{target_ext}/module/closesthit')
print(f'[I] compiled closesthit (module)')
cmd = compile_cmd(hit, f'targets/dxr-ah-modules', stage='anyhit', entry='MdlRadianceAnyHitProgram', emit=True)
run(cmd, f'full/{target_ext}/module/anyhit')
print(f'[I] compiled anyhit (module)')
cmd = compile_cmd(hit, f'targets/dxr-sh-modules', stage='anyhit', entry='MdlShadowAnyHitProgram', emit=True)
run(cmd, f'full/{target_ext}/module/shadow')
print(f'[I] compiled shadow (module)')
# Module precompilation time
precompilation_time = 0
for k in timings:
if k.startswith('module'):
precompilation_time += timings[k]['compileInner']
timings[f'full/{target_ext}/precompilation'] = { 'compileInner': precompilation_time }
# Output to benchmark file
json_data = []
for k, v in timings.items():
if not k.startswith('full'):
continue
name = k.split('/')[1:]
name = ' : '.join(reversed(name))
data = {
'name': name,
'unit': 'milliseconds',
'value': v['compileInner']
}
json_data.append(data)
# TODO: append target to benchmark file name
with open(args.output, 'w') as file:
json.dump(json_data, file, indent=4)
# Generate readable Markdown as well
print(4 * '\n')
print('# Slang MDL benchmark results\n')
print('## Module precompilation time\n')
print(f'Total: **{timings[f'full/{target_ext}/precompilation']['compileInner']} ms**\n')
print('## Module compilation for entry points\n')
entries = [ 'Closest Hit', 'Any Hit', 'Shadow' ]
prefixes = [ 'closesthit', 'anyhit', 'shadow' ]
table = prettytable.PrettyTable()
table.set_style(prettytable.MARKDOWN)
table.field_names = [ 'Entry', 'Total' ]
total = 0
for entry, prefix in zip(entries, prefixes):
row = [ entry ]
db = timings[f'full/{target_ext}/module/{prefix}']
spCompile = db['compileInner']
row.append(f'{spCompile:.3f}s')
table.add_row(row)
total += spCompile
print(f'Total: **{total} ms**\n')
print(table, end='\n\n')
print('## Monolithic compilation for entry points\n')
table = prettytable.PrettyTable()
table.set_style(prettytable.MARKDOWN)
table.field_names = [ 'Entry', 'Total' ]
total = 0
for entry, prefix in zip(entries, prefixes):
row = [ entry ]
db = timings[f'full/{target_ext}/mono/{prefix}']
spCompile = db['compileInner']
row.append(f'{spCompile:.3f}s')
table.add_row(row)
total += spCompile
print(f'Total: **{total} ms**\n')
print(table, end='\n\n')
|