1"""
2Objective-C runtime wrapper for use by LLDB Python formatters
3
4part of The LLVM Compiler Infrastructure
5This file is distributed under the University of Illinois Open Source
6License. See LICENSE.TXT for details.
7"""
8import lldb
9import time, datetime
10import inspect
11
12class TimeMetrics:
13	@staticmethod
14	def generate(label=None):
15		return TimeMetrics(label)
16
17	def __init__(self,lbl=None):
18		self.label = "" if lbl is None else lbl
19		pass
20
21	def __enter__(self):
22		caller = inspect.stack()[1]
23		self.function = str(caller)
24		self.enter_time = time.clock()
25
26	def __exit__(self, a,b,c):
27		self.exit_time = time.clock()
28		print "It took " + str(self.exit_time - self.enter_time) + " time units to run through " + self.function + self.label
29		return False
30
31class Counter:
32	def __init__(self):
33		self.count = 0
34		self.list = []
35	def update(self,name):
36		self.count = self.count + 1
37		# avoid getting the full dump of this ValueObject just to save its metrics
38		if isinstance(name,lldb.SBValue):
39			self.list.append(name.GetName())
40		else:
41			self.list.append(str(name))
42	def __str__(self):
43		return str(self.count) + " times, for items [" + str(self.list) + "]"
44
45class MetricsPrinter_Verbose:
46	def __init__(self,metrics):
47		self.metrics = metrics
48	def __str__(self):
49		string = ""
50		for key,value in self.metrics.metrics.items():
51			string = string + "metric " + str(key) + ": " + str(value) + "\n"
52		return string
53
54class MetricsPrinter_Compact:
55	def __init__(self,metrics):
56		self.metrics = metrics
57	def __str__(self):
58		string = ""
59		for key,value in self.metrics.metrics.items():
60			string = string + "metric " + str(key) + " was hit " + str(value.count) + " times\n"
61		return string
62
63class Metrics:
64	def __init__(self):
65		self.metrics = {}
66
67	def add_metric(self,name):
68		self.metrics[name] = Counter()
69
70	def metric_hit(self,metric,trigger):
71		self.metrics[metric].update(trigger)
72
73	def __getitem__(self,key):
74		return self.metrics[key]
75
76	def __getattr__(self,name):
77		if name == 'compact':
78			return MetricsPrinter_Compact(self)
79		if name == 'verbose':
80			return MetricsPrinter_Verbose(self)
81		raise AttributeError("%r object has no attribute %r" %
82			                         (type(self).__name__, name))
83
84	def __str__(self):
85		return str(self.verbose)
86
87	def metric_success(self,metric):
88		total_count = 0
89		metric_count = self[metric].count
90		for key,value in self.metrics.items():
91			total_count = total_count + value.count
92		if total_count > 0:
93			return metric_count / float(total_count)
94		return 0
95