120 lines · python
1"""2Objective-C runtime wrapper for use by LLDB Python formatters3 4Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.5See https://llvm.org/LICENSE.txt for license information.6SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception7"""8import lldb9import time10import datetime11import inspect12 13 14class TimeMetrics:15 @staticmethod16 def generate(label=None):17 return TimeMetrics(label)18 19 def __init__(self, lbl=None):20 self.label = "" if lbl is None else lbl21 pass22 23 def __enter__(self):24 caller = inspect.stack()[1]25 self.function = str(caller)26 self.enter_time = time.clock()27 28 def __exit__(self, a, b, c):29 self.exit_time = time.clock()30 print(31 "It took "32 + str(self.exit_time - self.enter_time)33 + " time units to run through "34 + self.function35 + self.label36 )37 return False38 39 40class Counter:41 def __init__(self):42 self.count = 043 self.list = []44 45 def update(self, name):46 self.count = self.count + 147 # avoid getting the full dump of this ValueObject just to save its48 # metrics49 if isinstance(name, lldb.SBValue):50 self.list.append(name.GetName())51 else:52 self.list.append(str(name))53 54 def __str__(self):55 return str(self.count) + " times, for items [" + str(self.list) + "]"56 57 58class MetricsPrinter_Verbose:59 def __init__(self, metrics):60 self.metrics = metrics61 62 def __str__(self):63 string = ""64 for key, value in self.metrics.metrics.items():65 string = string + "metric " + str(key) + ": " + str(value) + "\n"66 return string67 68 69class MetricsPrinter_Compact:70 def __init__(self, metrics):71 self.metrics = metrics72 73 def __str__(self):74 string = ""75 for key, value in self.metrics.metrics.items():76 string = (77 string78 + "metric "79 + str(key)80 + " was hit "81 + str(value.count)82 + " times\n"83 )84 return string85 86 87class Metrics:88 def __init__(self):89 self.metrics = {}90 91 def add_metric(self, name):92 self.metrics[name] = Counter()93 94 def metric_hit(self, metric, trigger):95 self.metrics[metric].update(trigger)96 97 def __getitem__(self, key):98 return self.metrics[key]99 100 def __getattr__(self, name):101 if name == "compact":102 return MetricsPrinter_Compact(self)103 if name == "verbose":104 return MetricsPrinter_Verbose(self)105 raise AttributeError(106 "%r object has no attribute %r" % (type(self).__name__, name)107 )108 109 def __str__(self):110 return str(self.verbose)111 112 def metric_success(self, metric):113 total_count = 0114 metric_count = self[metric].count115 for key, value in self.metrics.items():116 total_count = total_count + value.count117 if total_count > 0:118 return metric_count / float(total_count)119 return 0120