From 93c2eab854ac7adccf17032e02a25953c0baad16 Mon Sep 17 00:00:00 2001 From: Grigori Fursin Date: Fri, 18 Oct 2024 18:18:43 +0200 Subject: [PATCH] Added self-profile (-profile): https://github.com/mlcommons/ck/issues/1331 --- cm/cmind/core.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/cm/cmind/core.py b/cm/cmind/core.py index 85e18e39f..69411b639 100644 --- a/cm/cmind/core.py +++ b/cm/cmind/core.py @@ -842,7 +842,7 @@ def x(self, i, out = None): 'h', 'help', 'version', 'out', 'j', 'json', 'save_to_json_file', 'save_to_yaml_file', 'common', 'ignore_inheritance', 'log', 'logfile', 'raise', 'repro', - 'f', 'time']] + 'f', 'time', 'profile']] if len(unknown_control_flags)>0: unknown_control_flags_str = ','.join(unknown_control_flags) @@ -855,11 +855,13 @@ def x(self, i, out = None): if control.pop('f', ''): i['f'] = True - self_time = control.pop('time', False) + self_time = control.get('time', False) if not x_was_called and self_time: import time self_time1 = time.time() + self_profile = control.get('profile', False) + # Check repro use_log = str(control_flags.pop('log', '')).strip().lower() log_file = control_flags.pop('logfile', '') @@ -933,6 +935,13 @@ def x(self, i, out = None): self.log(f"x input: {spaces} ({i})", "debug") # Call access helper + if not x_was_called and self_profile: + # https://docs.python.org/3/library/profile.html#module-cProfile + import cProfile, pstats, io + from pstats import SortKey + profile = cProfile.Profile() + profile.enable() + r = self._x(i, control) if not self.logger == None: @@ -941,6 +950,17 @@ def x(self, i, out = None): self.state['recursion'] = recursion if not x_was_called: + if self_profile: + profile.disable() + s = io.StringIO() + sortby = SortKey.CUMULATIVE + ps = pstats.Stats(profile, stream=s).sort_stats(sortby) + ps.print_stats(32) + print ('') + print ('CMX profile:') + print ('') + print (s.getvalue()) + # Very first call (not recursive) # Check if output to json and save file