Implement benchmarking script in python
[platform/upstream/glibc.git] / scripts / bench.py
1 #!/usr/bin/python
2 # Copyright (C) 2014 Free Software Foundation, Inc.
3 # This file is part of the GNU C Library.
4 #
5 # The GNU C Library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License, or (at your option) any later version.
9 #
10 # The GNU C Library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with the GNU C Library; if not, see
17 # <http://www.gnu.org/licenses/>.
18
19 """Benchmark program generator script
20
21 This script takes a function name as input and generates a program using
22 an input file located in the benchtests directory.  The name of the
23 input file should be of the form foo-inputs where 'foo' is the name of
24 the function.
25 """
26
27 from __future__ import print_function
28 import sys
29 import os
30 import itertools
31
32 # Macro definitions for functions that take no arguments.  For functions
33 # that take arguments, the STRUCT_TEMPLATE, ARGS_TEMPLATE and
34 # VARIANTS_TEMPLATE are used instead.
35 DEFINES_TEMPLATE = '''
36 #define CALL_BENCH_FUNC(v, i) %(func)s ()
37 #define NUM_VARIANTS (1)
38 #define NUM_SAMPLES(v) (1)
39 #define VARIANT(v) FUNCNAME "()"
40 '''
41
42 # Structures to store arguments for the function call.  A function may
43 # have its inputs partitioned to represent distinct performance
44 # characteristics or distinct flavors of the function.  Each such
45 # variant is represented by the _VARIANT structure.  The ARGS structure
46 # represents a single set of arguments.
47 STRUCT_TEMPLATE = '''
48 #define CALL_BENCH_FUNC(v, i) %(func)s (%(func_args)s)
49
50 struct args
51 {
52 %(args)s
53 };
54
55 struct _variants
56 {
57   const char *name;
58   int count;
59   struct args *in;
60 };
61 '''
62
63 # The actual input arguments.
64 ARGS_TEMPLATE = '''
65 struct args in%(argnum)d[%(num_args)d] = {
66 %(args)s
67 };
68 '''
69
70 # The actual variants, along with macros defined to access the variants.
71 VARIANTS_TEMPLATE = '''
72 struct _variants variants[%(num_variants)d] = {
73 %(variants)s
74 };
75
76 #define NUM_VARIANTS %(num_variants)d
77 #define NUM_SAMPLES(i) (variants[i].count)
78 #define VARIANT(i) (variants[i].name)
79 '''
80
81 # Epilogue for the generated source file.
82 EPILOGUE = '''
83 #define BENCH_FUNC(i, j) ({%(getret)s CALL_BENCH_FUNC (i, j);})
84 #define FUNCNAME "%(func)s"
85 #include "bench-skeleton.c"'''
86
87
88 def gen_source(func, directives, all_vals):
89     """Generate source for the function
90
91     Generate the C source for the function from the values and
92     directives.
93
94     Args:
95       func: The function name
96       directives: A dictionary of directives applicable to this function
97       all_vals: A dictionary input values
98     """
99     # The includes go in first.
100     for header in directives['includes']:
101         print('#include <%s>' % header)
102
103     for header in directives['include-sources']:
104         print('#include "%s"' % header)
105
106     # Print macros.  This branches out to a separate routine if
107     # the function takes arguments.
108     if not directives['args']:
109         print(DEFINES_TEMPLATE % {'func': func})
110         outargs = []
111     else:
112         outargs = _print_arg_data(func, directives, all_vals)
113
114     # Print the output variable definitions if necessary.
115     for out in outargs:
116         print(out)
117
118     # If we have a return value from the function, make sure it is
119     # assigned to prevent the compiler from optimizing out the
120     # call.
121     if directives['ret']:
122         print('static %s volatile ret;' % directives['ret'])
123         getret = 'ret = '
124     else:
125         getret = ''
126
127     print(EPILOGUE % {'getret': getret, 'func': func})
128
129
130 def _print_arg_data(func, directives, all_vals):
131     """Print argument data
132
133     This is a helper function for gen_source that prints structure and
134     values for arguments and their variants and returns output arguments
135     if any are found.
136
137     Args:
138       func: Function name
139       directives: A dictionary of directives applicable to this function
140       all_vals: A dictionary input values
141
142     Returns:
143       Returns a list of definitions for function arguments that act as
144       output parameters.
145     """
146     # First, all of the definitions.  We process writing of
147     # CALL_BENCH_FUNC, struct args and also the output arguments
148     # together in a single traversal of the arguments list.
149     func_args = []
150     arg_struct = []
151     outargs = []
152
153     for arg, i in zip(directives['args'], itertools.count()):
154         if arg[0] == '<' and arg[-1] == '>':
155             pos = arg.rfind('*')
156             if pos == -1:
157                 die('Output argument must be a pointer type')
158
159             outargs.append('static %s out%d;' % (arg[1:pos], i))
160             func_args.append(' &out%d' % i)
161         else:
162             arg_struct.append('  %s volatile arg%d;' % (arg, i))
163             func_args.append('variants[v].in[i].arg%d' % i)
164
165     print(STRUCT_TEMPLATE % {'args' : '\n'.join(arg_struct), 'func': func,
166                              'func_args': ', '.join(func_args)})
167
168     # Now print the values.
169     variants = []
170     for (k, vals), i in zip(all_vals.items(), itertools.count()):
171         out = ['  {%s},' % v for v in vals]
172
173         # Members for the variants structure list that we will
174         # print later.
175         variants.append('  {"%s(%s)", %d, in%d},' % (func, k, len(vals), i))
176         print(ARGS_TEMPLATE % {'argnum': i, 'num_args': len(vals),
177                                'args': '\n'.join(out)})
178
179     # Print the variants and the last set of macros.
180     print(VARIANTS_TEMPLATE % {'num_variants': len(all_vals),
181                                'variants': '\n'.join(variants)})
182     return outargs
183
184
185 def _process_directive(d_name, d_val):
186     """Process a directive.
187
188     Evaluate the directive name and value passed and return the
189     processed value. This is a helper function for parse_file.
190
191     Args:
192       d_name: Name of the directive
193       d_val: The string value to process
194
195     Returns:
196       The processed value, which may be the string as it is or an object
197       that describes the directive.
198     """
199     # Process the directive values if necessary.  name and ret don't
200     # need any processing.
201     if d_name.startswith('include'):
202         d_val = d_val.split(',')
203     elif d_name == 'args':
204         d_val = d_val.split(':')
205
206     # Return the values.
207     return d_val
208
209
210 def parse_file(func):
211     """Parse an input file
212
213     Given a function name, open and parse an input file for the function
214     and get the necessary parameters for the generated code and the list
215     of inputs.
216
217     Args:
218       func: The function name
219
220     Returns:
221       A tuple of two elements, one a dictionary of directives and the
222       other a dictionary of all input values.
223     """
224     all_vals = {}
225     # Valid directives.
226     directives = {
227             'name': '',
228             'args': [],
229             'includes': [],
230             'include-sources': [],
231             'ret': ''
232     }
233
234     try:
235         with open('%s-inputs' % func) as f:
236             for line in f:
237                 # Look for directives and parse it if found.
238                 if line.startswith('##'):
239                     try:
240                         d_name, d_val = line[2:].split(':', 1)
241                         d_name = d_name.strip()
242                         d_val = d_val.strip()
243                         directives[d_name] = _process_directive(d_name, d_val)
244                     except (IndexError, KeyError):
245                         die('Invalid directive: %s' % line[2:])
246
247                 # Skip blank lines and comments.
248                 line = line.split('#', 1)[0].rstrip()
249                 if not line:
250                     continue
251
252                 # Otherwise, we're an input.  Add to the appropriate
253                 # input set.
254                 cur_name = directives['name']
255                 all_vals.setdefault(cur_name, [])
256                 all_vals[cur_name].append(line)
257     except IOError as ex:
258         die("Failed to open input file (%s): %s" % (ex.filename, ex.strerror))
259
260     return directives, all_vals
261
262
263 def die(msg):
264     """Exit with an error
265
266     Prints an error message to the standard error stream and exits with
267     a non-zero status.
268
269     Args:
270       msg: The error message to print to standard error
271     """
272     print('%s\n' % msg, file=sys.stderr)
273     sys.exit(os.EX_DATAERR)
274
275
276 def main(args):
277     """Main function
278
279     Use the first command line argument as function name and parse its
280     input file to generate C source that calls the function repeatedly
281     for the input.
282
283     Args:
284       args: The command line arguments with the program name dropped
285
286     Returns:
287       os.EX_USAGE on error and os.EX_OK on success.
288     """
289     if len(args) != 1:
290         print('Usage: %s <function>' % sys.argv[0])
291         return os.EX_USAGE
292
293     directives, all_vals = parse_file(args[0])
294     gen_source(args[0], directives, all_vals)
295     return os.EX_OK
296
297
298 if __name__ == '__main__':
299     sys.exit(main(sys.argv[1:]))