forked from graalvm/mx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mx_benchmark.py
2815 lines (2307 loc) · 113 KB
/
mx_benchmark.py
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# ----------------------------------------------------------------------------------------------------
#
# Copyright (c) 2018, 2016, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# ----------------------------------------------------------------------------------------------------
from __future__ import print_function
import sys
import json
import os.path
import platform
import re
import socket
import time
import traceback
import uuid
import tempfile
import shutil
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
from argparse import SUPPRESS
from collections import OrderedDict
import mx
_bm_suites = {}
_benchmark_executor = None
def mx_benchmark_compatibility():
"""Get the required compatibility version from the mx primary suite.
:rtype: MxCompatibility500
"""
return mx.primary_suite().getMxCompatibility()
_profilers = {}
class JVMProfiler(object):
"""
Encapsulates the name and how to trigger common VM profilers.
"""
def __init__(self):
self.nextItemName = None
def name(self):
raise NotImplementedError()
def setup(self, benchmarks, bmSuiteArgs):
if benchmarks:
self.nextItemName = benchmarks[0]
else:
self.nextItemName = None
def sets_vm_prefix(self):
return False
def additional_options(self, dump_path):
"""
Returns a tuple of a list extra JVM options to be added to the command line, plus an optional
set of arguments that will be inserted as a command prefix.
"""
return [], None
def register_profiler(obj):
if not isinstance(obj, JVMProfiler):
raise ValueError("Cannot register profiler. Profilers must be of type {}".format(JVMProfiler.__class__.__name__))
if obj.name() in _profilers:
raise ValueError("A profiler with name '{}' is already registered!")
_profilers[obj.name()] = obj
class SimpleJFRProfiler(JVMProfiler):
"""
A simple JFR profiler with reasonable defaults.
"""
def name(self):
return "JFR"
def additional_options(self, dump_path):
if self.nextItemName:
import datetime
filename = os.path.join(dump_path, "{}_{}.jfr".format(self.nextItemName,
datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S")))
else:
filename = dump_path
common_opts = [
"-XX:+UnlockDiagnosticVMOptions",
"-XX:+DebugNonSafepoints",
"-XX:+FlightRecorder"
]
if mx.get_jdk().javaCompliance >= '9':
opts = common_opts + [
"-XX:StartFlightRecording=settings=profile,disk=false,maxsize=200M,dumponexit=true,filename={}".format(filename),
"-Xlog:jfr=info"
]
elif mx.get_jdk().is_openjdk_based():
# No logging levels on OpenJDK 8.
# Alternatively, one can use -XX:+LogJFR for 'trace' level
opts = common_opts + [
"-XX:+UnlockCommercialFeatures",
"-XX:StartFlightRecording=settings=profile,disk=false,maxsize=200M,dumponexit=true,filename={}".format(filename)
]
else:
opts = ["-XX:+UnlockCommercialFeatures"] + common_opts + [
"-XX:StartFlightRecording=defaultrecording=true,settings=profile,filename={}".format(filename),
"-XX:FlightRecorderOptions=loglevel=info,disk=false,maxsize=200M,dumponexit=true"
]
# reset the next item name since it has just been consumed
self.nextItemName = None
return opts, None
class AsyncProfiler(JVMProfiler):
"""
Produces svg flame graphs using async-profiler (https://github.com/jvm-profiling-tools/async-profiler)
"""
def name(self):
return "async"
def version(self):
return "1.8.3"
def libraryPath(self):
async_profiler_lib = mx.library("ASYNC_PROFILER_{}".format(self.version()))
if not async_profiler_lib.is_available():
raise mx.abort("'--profiler {}' is not supported on '{}/{}' because the '{}' library is not available."
.format(self.name(), mx.get_os(), mx.get_arch(), async_profiler_lib.name))
libraryDirectory = async_profiler_lib.get_path(True)
innerDir = [f for f in os.listdir(libraryDirectory) if os.path.isdir(os.path.join(libraryDirectory, f))][0]
return os.path.join(libraryDirectory, innerDir, "build", "libasyncProfiler.so")
def additional_options(self, dump_path):
import datetime
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S")
if self.nextItemName:
filename = os.path.join(dump_path, "{}_{}.svg".format(self.nextItemName, timestamp))
else:
filename = os.path.join(dump_path, "{}.svg".format(timestamp))
opts = ["-agentpath:{}=start,file={}".format(self.libraryPath(), filename)]
# reset the next item name since it has just been consumed
self.nextItemName = None
return opts, None
register_profiler(SimpleJFRProfiler())
register_profiler(AsyncProfiler())
# Contains an argument parser and its description.
class ParserEntry(object):
def __init__(self, parser, description):
"""
:param ArgumentParser parser: the parser
:param str description: the description
"""
self.parser = parser
self.description = description
# Parsers used by different `mx benchmark` commands.
parsers = {}
_mx_benchmark_usage_example = "mx benchmark <suite>:<bench>"
def add_parser(name, parser_entry):
"""Add a named parser to be used in benchmark suites.
:param str name: the name of the parser
:param ParserEntry parser_entry: the parser and description
:return:
"""
if name in parsers:
mx.abort("There is already a parser called '{}'".format(name))
parsers[name] = parser_entry
def get_parser(name):
"""Gets the named parser
:param str name: the name of the parser
:rtype: ArgumentParser
"""
return parsers[name].parser
class VmRegistry(object):
def __init__(self, vm_type_name, short_vm_type_name=None, default_vm=None, known_host_registries=None):
"""
:param str vm_type_name: full VM type name (e.g., "Java")
:param str short_vm_type_name:
:param default_vm: a callable which, given a config name gives a default VM name
:param list[VmRegistry] known_host_registries: a list of known host VM registries
"""
self.vm_type_name = vm_type_name + " VM"
self.short_vm_type_name = short_vm_type_name if short_vm_type_name else vm_type_name.lower() + "-vm"
assert default_vm is None or callable(default_vm)
self.default_vm = default_vm
assert re.compile(r"\A[a-z-]+\Z").match(self.short_vm_type_name)
self._vms = OrderedDict()
self._vms_suite = {}
self._vms_priority = {}
self._known_host_registries = known_host_registries or []
add_parser(self.get_parser_name(), ParserEntry(
ArgumentParser(add_help=False, usage=_mx_benchmark_usage_example + " -- <options> -- ..."),
"\n\n{} selection flags, specified in the benchmark suite arguments:\n".format(self.vm_type_name)
))
get_parser(self.get_parser_name()).add_argument("--profiler", default=None, help="The profiler to use")
get_parser(self.get_parser_name()).add_argument("--{}".format(self.short_vm_type_name), default=None, help="{vm} to run the benchmark with.".format(vm=self.vm_type_name))
get_parser(self.get_parser_name()).add_argument("--{}-config".format(self.short_vm_type_name), default=None, help="{vm} configuration for the selected {vm}.".format(vm=self.vm_type_name))
# Separator to stack guest and host VM options. Though ignored, must be consumed by the parser.
get_parser(self.get_parser_name()).add_argument('--guest', action='store_true', dest=SUPPRESS, default=None, help='Separator for --{vm}=host --guest --{vm}=guest VM configurations.'.format(vm=self.short_vm_type_name))
def get_parser_name(self):
return self.vm_type_name + "_parser"
def get_known_guest_registries(self):
return self._known_host_registries
def get_default_vm(self, config):
if self.default_vm:
return self.default_vm(config, self._vms)
return None
def get_available_vm_configs_help(self):
avail = ['--{}={} --{}-config={}'.format(self.short_vm_type_name, vm.name(), self.short_vm_type_name, vm.config_name()) for vm in self._vms.values()]
return 'The following {} configurations are available:\n {}'.format(self.vm_type_name, '\n '.join(avail))
def get_vm_from_suite_args(self, bmSuiteArgs, hosted=False, quiet=False, host_vm_only_as_default=False):
"""
Helper function for suites or other VMs that need to create a JavaVm based on mx benchmark arguments.
Suites that might need this should add `java_vm_parser_name` to their `parserNames`.
:param list[str] bmSuiteArgs: the suite args provided by mx benchmark
:param boolean host_vm_only_as_default:
if true and `bmSuiteArgs` does not specify a VM, picks a host VM as default, discarding guest VMs.
:return: a Vm as configured by the `bmSuiteArgs`.
:rtype: Vm
"""
vm_config_args = splitArgs(bmSuiteArgs, '--')[0]
# Use --guest as separator to stack guest VMs (also within the same registry) e.g. --jvm=host_vm --guest --jvm=guest_vm.
rest, args = rsplitArgs(vm_config_args, '--guest')
check_guest_vm = '--guest' in vm_config_args
args, unparsed_args = get_parser(self.get_parser_name()).parse_known_args(args)
bmSuiteArgsPending = rest + unparsed_args
arg_vm_type_name = self.short_vm_type_name.replace('-', '_')
vm = getattr(args, arg_vm_type_name)
vm_config = getattr(args, arg_vm_type_name + '_config')
if vm is None:
vm = self.get_default_vm(vm_config)
if vm is None:
vms = [(vm,
self._vms_suite[(vm, config)] == mx.primary_suite(),
('hosted' in config) == hosted,
self._vms_priority[(vm, config)]
) for (vm, config), vm_obj in self._vms.items() if (vm_config is None or config == vm_config) and not (host_vm_only_as_default and isinstance(vm_obj, GuestVm))]
if not vms:
mx.abort("Could not find a {} to default to.\n{avail}".format(self.vm_type_name, avail=self.get_available_vm_configs_help()))
vms.sort(key=lambda t: t[1:], reverse=True)
vm = vms[0][0]
if len(vms) == 1:
notice = mx.log
choice = vm
else:
notice = mx.warn
seen = set()
choice = ' [' + '|'.join((c[0] for c in vms if c[0] not in seen and (seen.add(c[0]) or True))) + ']'
if not quiet:
notice("Defaulting the {} to '{}'. Consider using --{} {}".format(self.vm_type_name, vm, self.short_vm_type_name, choice))
if vm_config is None:
vm_configs = [(config,
self._vms_suite[(vm, config)] == mx.primary_suite(),
('hosted' in config) == hosted,
self._vms_priority[(vm, config)]
) for (j, config) in self._vms if j == vm]
if not vm_configs:
mx.abort("Could not find a {vm_type} config to default to for {vm_type} '{vm}'.\n{avail}".format(vm=vm, vm_type=self.vm_type_name, avail=self.get_available_vm_configs_help()))
vm_configs.sort(key=lambda t: t[1:], reverse=True)
vm_config = vm_configs[0][0]
if len(vm_configs) == 1:
notice = mx.log
choice = vm_config
else:
notice = mx.warn
seen = set()
choice = ' [' + '|'.join((c[0] for c in vm_configs if c[0] not in seen and (seen.add(c[0]) or True))) + ']'
if not quiet:
notice("Defaulting the {} config to '{}'. Consider using --{}-config {}.".format(self.vm_type_name, vm_config, self.short_vm_type_name, choice))
vm_object = self.get_vm(vm, vm_config)
if check_guest_vm and not isinstance(vm_object, GuestVm):
mx.abort("{vm_type} '{vm}' with config '{vm_config}' is declared as --guest but it's NOT a guest VM.".format(vm=vm, vm_type=self.vm_type_name, vm_config=vm_config))
if isinstance(vm_object, GuestVm):
host_vm = vm_object.hosting_registry().get_vm_from_suite_args(bmSuiteArgsPending, hosted=True, quiet=quiet, host_vm_only_as_default=True)
vm_object = vm_object.with_host_vm(host_vm)
return vm_object
def add_vm(self, vm, suite=None, priority=0):
key = (vm.name(), vm.config_name())
if key in self._vms:
mx.abort("{} and config '{}' already exist.".format(self.vm_type_name, key))
self._vms[key] = vm
self._vms_suite[key] = suite
self._vms_priority[key] = priority
def get_vm(self, vm_name, vm_config):
key = (vm_name, vm_config)
if key not in self._vms:
mx.abort("{} and config '{}' do not exist.\n{}".format(self.vm_type_name, key, self.get_available_vm_configs_help()))
return self._vms[key]
def get_vms(self):
return list(self._vms.values())
# JMH suite parsers.
add_parser("jmh_jar_benchmark_suite_vm", ParserEntry(
ArgumentParser(add_help=False, usage=_mx_benchmark_usage_example + " -- <options> -- ..."),
"\n\nVM selection flags for JMH benchmark suites:\n"
))
get_parser("jmh_jar_benchmark_suite_vm").add_argument("--jmh-jar", default=None)
get_parser("jmh_jar_benchmark_suite_vm").add_argument("--jmh-name", default=None)
get_parser("jmh_jar_benchmark_suite_vm").add_argument("--jmh-benchmarks", default=None)
class BenchmarkSuite(object):
"""
A harness for a benchmark suite.
A suite needs to be registered with mx_benchmarks.add_bm_suite.
"""
def __init__(self, *args, **kwargs):
super(BenchmarkSuite, self).__init__(*args, **kwargs)
self._desired_version = None
self._suite_dimensions = {}
self._command_mapper_hooks = []
self._currently_running_benchmark = None
def name(self):
"""Returns the name of the suite to execute.
:return: Name of the suite.
:rtype: str
"""
raise NotImplementedError()
def benchSuiteName(self, bmSuiteArgs=None):
"""Returns the name of the actual suite that is being executed, independent of the fact it's a suite variant
which is configured or compiled differently.
Example:
- `benchSuiteName`: 'dacapo'
- `name`: 'dacapo-timing' or 'dacapo-native-image'
:return: Name of the suite.
:rtype: str
"""
return self.name()
def group(self):
"""The group that this benchmark suite belongs to, for example, `Graal`.
This is the name of the overall group of closely related projects.
:return: Name of the group.
:rtype: str
"""
raise NotImplementedError()
def subgroup(self):
"""The subgroup that this suite belongs to, e.g., `fastr` or `graal-compiler`.
This is the name of the subteam project within the group.
:return: Name of the subgroup.
:rtype: str
"""
raise NotImplementedError()
def benchmarkList(self, bmSuiteArgs):
"""Returns the list of the benchmarks provided by this suite.
:param list[str] bmSuiteArgs: List of string arguments to the suite.
:return: List of benchmark string names.
:rtype: list[str]
"""
raise NotImplementedError()
def currently_running_benchmark(self):
"""
:return: The name of the benchmark being currently executed or None otherwise.
"""
return self._currently_running_benchmark
def register_command_mapper_hook(self, name, func):
"""Registers a function that takes as input the benchmark suite object and the command to execute and returns
a modified command line.
:param function func:
:return: None
"""
self._command_mapper_hooks.append((name, func, self))
def version(self):
"""The suite version selected for execution which is either the :defaultSuiteVerion:
or the :desiredVersion: if any.
NOTE: This value is present in the result file for suite identification.
:return: actual version.
:rtype: str
"""
current_version = self.defaultSuiteVersion()
selected_version = self.desiredVersion() if self.desiredVersion() else current_version
if selected_version not in self.availableSuiteVersions():
mx.abort("Available suite versions are: {}".format(self.availableSuiteVersions()))
return selected_version
def defaultSuiteVersion(self):
""" The default benchmark version to use.
:return: default version.
"""
return "unknown"
def availableSuiteVersions(self):
"""List of available versions of that benchmark suite.
:return: list of version strings.
:rtype: list[str]
"""
return [self.defaultSuiteVersion()]
def desiredVersion(self):
"""Returns the benchmark suite version that is requested for execution.
:return: suite version.
:rtype: str
"""
return self._desired_version
def setDesiredVersion(self, version):
self._desired_version = version
def validateEnvironment(self):
"""Validates the environment and raises exceptions if validation fails.
Can be overridden to check for existence of required environment variables
before the benchmark suite executed.
"""
pass
def vmArgs(self, bmSuiteArgs):
"""Extracts the VM flags from the list of arguments passed to the suite.
:param list[str] bmSuiteArgs: List of string arguments to the suite.
:return: A list of string flags that are VM flags.
:rtype: list[str]
"""
raise NotImplementedError()
def runArgs(self, bmSuiteArgs):
"""Extracts the run flags from the list of arguments passed to the suite.
:param list[str] bmSuiteArgs: List of string arguments to the suite.
:return: A list of string flags that are arguments for the suite.
:rtype: list[str]
"""
raise NotImplementedError()
def before(self, bmSuiteArgs):
"""Called exactly once before any benchmark invocations begin.
Useful for outputting information such as platform version, OS, etc.
Arguments: see `run`.
"""
def after(self, bmSuiteArgs):
"""Called exactly once after all benchmark invocations are done.
Useful for cleaning up after the benchmarks.
Arguments: see `run`.
"""
def parserNames(self):
"""Returns the list of parser names that this benchmark suite uses.
This is used to more accurately show command line options tied to a specific
benchmark suite.
:rtype: list[str]
"""
return []
def suiteDimensions(self):
"""Returns context specific dimensions that will be integrated in the measurement
data.
:rtype: dict
"""
return self._suite_dimensions
def run(self, benchmarks, bmSuiteArgs):
"""Runs the specified benchmarks with the given arguments.
More precisely, if `benchmarks` is a list, runs the list of the benchmarks from
the suite in one run (typically, one VM invocations). If `benchmarks` is None,
then it runs all the benchmarks from the suite.
.. note:: A benchmark suite may not support running multiple benchmarks,
or None, but it must at least run with a single benchmark in the
`benchmarks` list.
:param benchmarks: List of benchmark string names, or a None.
:type benchmarks: list or None
:param list bmSuiteArgs: List of string arguments to the suite.
:return:
List of measurement result dictionaries, each corresponding to a datapoint.
A measurement result is an object that can be converted into JSON and is
merged with the other dimensions of the data point.
A measurement result must contain a field `metric`, which has the following
values:
- `metric.name` -- name of the metric (e.g. `"time"`, `"memory"`, ...)
- `metric.value` -- value of the measurement (e.g. `1.54`)
- `metric.unit` -- a string that specified the unit of measurement
(e.g. `"ms"`)
- `metric.score-function` -- name of the scoring function for the result
(e.g. `id`, which just returns the measurement value)
- `metric.score-value` -- score of the value, evaluated by the specified
scoring function (e.g. `"1.54"`)
- `metric.type` -- a string denoting the type of the metric
(e.g. `"numeric"`)
- `metric.better` -- `"higher"` if higher is better, `"lower"` otherwise
- `metric.iteration` -- iteration number of the measurement (e.g. `0`)
:rtype: object
"""
raise NotImplementedError()
def dump_results_file(self, file_path, data_points):
if not data_points:
return 0
dump = json.dumps({"queries": data_points}, sort_keys=True, indent=2)
with open(file_path, "w") as txtfile:
txtfile.write(dump)
file_size_kb = int(os.path.getsize(file_path) / 1024)
mx.log("{} benchmark data points dumped to {} ({} KB)".format(len(data_points), file_path, file_size_kb))
return len(data_points)
def workingDirectory(self, benchmarks, bmSuiteArgs):
"""Returns the desired working directory for running the benchmark.
By default it returns `None`, meaning that the working directory is not be
changed. It is meant to be overridden in subclasses when necessary.
"""
return None
def add_bm_suite(suite, mxsuite=None):
if mxsuite is None:
mxsuite = mx.currently_loading_suite.get()
full_name = "{}-{}".format(suite.name(), suite.subgroup())
if full_name in _bm_suites:
raise RuntimeError("Benchmark suite full name '{0}' already exists.".format(full_name))
_bm_suites[full_name] = suite
setattr(suite, ".mxsuite", mxsuite)
simple_name = suite.name()
# If possible also register suite with simple_name
if simple_name in _bm_suites:
if _bm_suites[simple_name]:
mx.log("Warning: Benchmark suite '{0}' name collision. Suites only available as '{0}-<subgroup>'.".format(simple_name))
_bm_suites[simple_name] = None
else:
_bm_suites[simple_name] = suite
def bm_suite_valid_keys():
return sorted([k for k, v in _bm_suites.items() if v])
def vm_registries():
res = set()
for bm_suite in _bm_suites.values():
if isinstance(bm_suite, VmBenchmarkSuite):
res.add(bm_suite.get_vm_registry())
return res
class Rule(object):
# the maximum size of a string field
max_string_field_length = 255
@staticmethod
def crop_front(prefix=""):
"""Returns a function that truncates a string at the start."""
assert len(prefix) < Rule.max_string_field_length
def _crop(path):
if len(path) < Rule.max_string_field_length:
return str(path)
return str(prefix + path[-(Rule.max_string_field_length-len(prefix)):])
return _crop
@staticmethod
def crop_back(suffix=""):
"""Returns a function that truncates a string at the end."""
assert len(suffix) < Rule.max_string_field_length
def _crop(path):
if len(path) < Rule.max_string_field_length:
return str(path)
return str(path[:Rule.max_string_field_length-len(suffix)] + suffix)
return _crop
def parse(self, text):
"""Create a dictionary of variables for every measurment.
:param text: The standard output of the benchmark.
:type text: str
:return: Iterable of dictionaries with the matched variables.
:rtype: iterable
"""
raise NotImplementedError()
def _prepend_working_dir(self, filename):
"""Prepends the current working directory to the filename.
Can only be called from within `parse()`.
"""
if hasattr(self, "_cwd") and self._cwd and not os.path.isabs(filename):
return os.path.join(self._cwd, filename)
return filename
class BaseRule(Rule):
"""A rule parses a raw result and a prepares a structured measurement using a replacement
template.
A replacement template is a dictionary that describes how to create a measurement:
{
"benchmark": ("<benchmark>", str),
"metric.name": "time",
"metric.value": ("<value>", int),
"metric.unit": "ms",
"metric.score-function": "id",
"metric.type": "numeric",
"metric.better": "lower",
"metric.iteration": ("$iteration", id),
}
When `instantiate` is called, the tuples in the template shown above are
replaced with the corresponding named groups from the parsing pattern, and converted
to the specified type.
Tuples can contain one of the following special variables, prefixed with a `$` sign:
- `iteration` -- ordinal number of the match that produced the datapoint, among
all the matches for that parsing rule.
"""
def __init__(self, replacement):
self.replacement = replacement
def parseResults(self, text):
"""Parses the raw result of a benchmark and create a dictionary of variables
for every measurment.
:param text: The standard output of the benchmark.
:type text: str
:return: Iterable of dictionaries with the matched variables.
:rtype: iterable
"""
raise NotImplementedError()
def parse(self, text):
datapoints = []
capturepat = re.compile(r"<([a-zA-Z_][0-9a-zA-Z_]*)>")
varpat = re.compile(r"\$([a-zA-Z_][0-9a-zA-Z_]*)")
for iteration, m in enumerate(self.parseResults(text)):
datapoint = {}
for key, value in self.replacement.items():
inst = value
if isinstance(inst, tuple):
v, vtype = inst
# Instantiate with named captured groups.
def var(name):
if name == "iteration":
return str(iteration)
else:
raise RuntimeError("Unknown var {0}".format(name))
v = varpat.sub(lambda vm: var(vm.group(1)), v)
v = capturepat.sub(lambda vm: m[vm.group(1)], v)
# Convert to a different type.
if vtype is str:
inst = str(v)
elif vtype is int:
inst = int(v)
elif vtype is float:
if isinstance(v, str) and ',' in v and '.' not in v:
# accommodate different locale in float formatting
v = v.replace(',', '.')
inst = float(v)
elif vtype is bool:
inst = bool(v)
elif hasattr(vtype, '__call__'):
inst = vtype(v)
else:
raise RuntimeError("Cannot handle object '{0}' of expected type {1}".format(v, vtype))
if not isinstance(inst, (str, int, float, bool)):
if type(inst).__name__ != 'long': # Python2: int(x) can result in a long
raise RuntimeError("Object '{}' has unknown type: {}".format(inst, type(inst)))
datapoint[key] = inst
datapoints.append(datapoint)
return datapoints
class StdOutRule(BaseRule):
"""Each rule contains a parsing pattern and a replacement template.
A parsing pattern is a regex that may contain any number of named groups,
as shown in the example:
r"===== DaCapo (?P<benchmark>[a-z]+) PASSED in (?P<value>[0-9]+) msec ====="
The above parsing regex captures the benchmark name into a variable `benchmark`
and the elapsed number of milliseconds into a variable called `value`.
"""
def __init__(self, pattern, replacement):
super(StdOutRule, self).__init__(replacement)
self.pattern = pattern
def parseResults(self, text):
return (m.groupdict() for m in re.finditer(self.pattern, text, re.MULTILINE))
class CSVBaseRule(BaseRule):
"""Parses a CSV file and creates a measurement result using the replacement."""
def __init__(self, colnames, replacement, filter_fn=None, **kwargs):
"""
:param colnames: list of column names of the CSV file. These names are used to
instantiate the replacement template.
:type colnames: list
:param filter_fn: function for filtering and transforming raw results
:type filter_fn: function
"""
super(CSVBaseRule, self).__init__(replacement)
self.colnames = colnames
self.kwargs = kwargs
self.filter_fn = filter_fn if filter_fn else self.filterResult
def filterResult(self, r):
"""Filters and transforms a raw result
:return: Dictionary of variables or None if the result should be omitted.
:rtype: dict or None
"""
return r
def getCSVFiles(self, text):
"""Get the CSV files which should be parsed.
:param text: The standard output of the benchmark.
:type text: str
:return: List of file names
:rtype: list
"""
raise NotImplementedError()
def parseResults(self, text):
import csv
l = []
files = self.getCSVFiles(text)
for filename in files:
with open(self._prepend_working_dir(filename), 'r') as csvfile:
csvReader = csv.DictReader(csvfile, fieldnames=self.colnames, **self.kwargs)
l = l + [r for r in (self.filter_fn(x) for x in csvReader) if r]
return l
class CSVFixedFileRule(CSVBaseRule):
"""CSV rule that parses a file with a predefined name."""
def __init__(self, filename, *args, **kwargs):
super(CSVFixedFileRule, self).__init__(*args, **kwargs)
self.filename = filename
def getCSVFiles(self, text):
return [self.filename]
class CSVStdOutFileRule(CSVBaseRule):
"""CSV rule that looks for CSV file names in the output of the benchmark."""
def __init__(self, pattern, match_name, *args, **kwargs):
super(CSVStdOutFileRule, self).__init__(*args, **kwargs)
self.pattern = pattern
self.match_name = match_name
def getCSVFiles(self, text):
return (m.groupdict()[self.match_name] for m in re.finditer(self.pattern, text, re.MULTILINE))
class JsonStdOutFileRule(BaseRule):
def __init__(self, pattern, match_name, replacement, keys):
super(JsonStdOutFileRule, self).__init__(replacement)
self.pattern = pattern
self.match_name = match_name
self.keys = keys
def parseResults(self, text):
l = []
for f in self.getFiles(text):
with open(f) as fp:
l = l + [{k:str(v)} for k, v in json.load(fp).items() if k in self.keys]
return l
def getFiles(self, text):
return (m.groupdict()[self.match_name] for m in re.finditer(self.pattern, text, re.MULTILINE))
class JMHJsonRule(Rule):
"""Parses a JSON file produced by JMH and creates a measurement result."""
extra_jmh_keys = [
"mode",
"threads",
"forks",
"warmupIterations",
"warmupTime",
"warmupBatchSize",
"measurementIterations",
"measurementTime",
"measurementBatchSize",
]
def __init__(self, filename, suiteName):
self.filename = filename
self.suiteName = suiteName
def shortenPackageName(self, benchmark):
"""
Returns an abbreviated name for the benchmark.
Example: com.example.benchmark.Bench -> c.e.b.Bench
The full name is stored in the `extra.jmh.benchmark` property.
"""
s = benchmark.split(".")
# class and method
clazz = s[-2:]
package = [str(x[0]) for x in s[:-2]]
return ".".join(package + clazz)
def getExtraJmhKeys(self):
return JMHJsonRule.extra_jmh_keys
def getBenchmarkNameFromResult(self, result):
return result["benchmark"]
def parse(self, text):
r = []
with open(self._prepend_working_dir(self.filename)) as fp:
for result in json.load(fp):
benchmark = self.getBenchmarkNameFromResult(result)
mode = result["mode"]
pm = result["primaryMetric"]
unit = pm["scoreUnit"]
unit_parts = unit.split("/")
if mode == "thrpt":
# Throughput, ops/time
metricName = "throughput"
better = "higher"
if len(unit_parts) == 2:
metricUnit = "op/" + unit_parts[1]
else:
metricUnit = unit
else:
# Average time, Sampling time, Single shot invocation time
better = "lower"
if len(unit_parts) == 2:
metricUnit = unit_parts[0]
else:
metricUnit = unit
if mode == "avgt":
metricName = "average-time"
elif mode == "sample":
metricName = "sample-time"
elif mode == "ss":
metricName = "single-shot"
else:
raise RuntimeError("Unknown benchmark mode {0}".format(mode))
d = {
"bench-suite" : self.suiteName,
"benchmark" : self.shortenPackageName(benchmark),
"metric.name": metricName,
"metric.unit": metricUnit,
"metric.score-function": "id",
"metric.better": better,
"metric.type": "numeric",
# full name
"extra.jmh.benchmark" : benchmark,
}
if "params" in result:
# add all parameter as a single string
d["extra.jmh.params"] = ", ".join(["=".join(kv) for kv in result["params"].items()])
# and also the individual values
for k, v in result["params"].items():
d["extra.jmh.param." + k] = str(v)
for k in self.getExtraJmhKeys():
if k in result:
d["extra.jmh." + k] = str(result[k])
if 'rawData' not in pm:
# we don't have the raw results, e.g. for the `sample` mode
# upload only the overall score
d.update({
"metric.value": float(pm['score']),
})
r.append(d)
else:
for jmhFork, rawData in enumerate(pm["rawData"]):
for iteration, data in enumerate(rawData):
d2 = d.copy()
d2.update({
"metric.value": float(data),
"metric.iteration": int(iteration),
"extra.jmh.fork": str(jmhFork),
})
r.append(d2)
return r
class BenchmarkFailureError(RuntimeError):
"""Thrown when a benchmark execution results in an error."""
def __init__(self, message, partialResults):
super(BenchmarkFailureError, self).__init__(message)
self.partialResults = partialResults
class StdOutBenchmarkSuite(BenchmarkSuite):
"""Convenience suite for benchmarks that need to parse standard output.
The standard output benchmark proceeds in the following steps:
1. Run the benchmark.
2. Terminate if there was a non-zero exit code.
3. Terminate if one of the specified failure patterns was matched.
4. Terminate if none of the specified success patterns was matched.
5. Use the parse rules on the standard output to create data points.
"""
def run(self, benchmarks, bmSuiteArgs):
runretval = self.runAndReturnStdOut(benchmarks, bmSuiteArgs)
if len(runretval) == 3:
retcode, out, dims = runretval
return self.validateStdoutWithDimensions(
out, benchmarks, bmSuiteArgs, retcode=retcode, dims=dims)
else:
# TODO: Remove old-style validateStdOut after updating downstream suites.
mx.log_deprecation("'runAndReturnStdOut' must return exactly three elements !")
retcode, out = runretval
return self.validateStdout(out, benchmarks, bmSuiteArgs, retcode=retcode)
# TODO: Remove once all the downstream suites become up-to-date.