# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) """Parse or generate representations of perf metrics.""" import ast import decimal import json import re from typing import Dict, List, Optional, Set, Tuple, Union
class Expression: """Abstract base class of elements in a metric expression."""
def _Constify(val: Union[bool, int, float, Expression]) -> Expression: """Used to ensure that the nodes in the expression tree are all Expression.""" if isinstance(val, bool): return Constant(1 if val else 0) if isinstance(val, (int, float)): return Constant(val) return val
# Simple lookup for operator precedence, used to avoid unnecessary # brackets. Precedence matches that of the simple expression parser # but differs from python where comparisons are lower precedence than # the bitwise &, ^, | but not the logical versions that the expression # parser doesn't have.
_PRECEDENCE = { '|': 0, '^': 1, '&': 2, '<': 3, '>': 3, '+': 4, '-': 4, '*': 5, '/': 5, '%': 5,
}
class Operator(Expression): """Represents a binary operator in the parse tree."""
def Bracket(self,
other: Expression,
other_str: str,
rhs: bool = False) -> str: """If necessary brackets the given other value.
If ``other`` is an operator then a bracket is necessary when
this/self operator has higher precedence. Consider: '(a + b) * c',
``other_str`` will be 'a + b'. A bracket is necessary as without
the bracket 'a + b * c' will evaluate 'b * c' first. However, '(a
* b) + c' doesn't need a bracket as'a * b' will always be
evaluated first. For'a / (b * c)' (ie the same precedence level
operations) then we add the bracket to best match the original
input, but notfor'(a / b) * c' where the bracket is unnecessary.
Args:
other (Expression): is a lhs or rhs operator
other_str (str): ``other`` in the appropriate string form
rhs (bool): is ``other`` on the RHS
Returns:
str: possibly bracketed other_str """ if isinstance(other, Operator): if _PRECEDENCE.get(self.operator, -1) > _PRECEDENCE.get(
other.operator, -1): return f'({other_str})' if rhs and _PRECEDENCE.get(self.operator, -1) == _PRECEDENCE.get(
other.operator, -1): return f'({other_str})' return other_str
if isinstance(self.lhs, Constant): if self.operator in ('+', '|') and lhs.value == '0': return rhs
# Simplify multiplication by 0 except for the slot event which # is deliberately introduced using this pattern. if self.operator == '*'and lhs.value == '0'and ( not isinstance(rhs, Event) or'slots'notin rhs.name.lower()): return Constant(0)
if self.operator == '*'and lhs.value == '1': return rhs
if isinstance(rhs, Constant): if self.operator in ('+', '|') and rhs.value == '0': return lhs
if self.operator == '*'and rhs.value == '0': return Constant(0)
if self.operator == '*'and self.rhs.value == '1': return lhs
return Operator(self.operator, lhs, rhs)
def Equals(self, other: Expression) -> bool: if isinstance(other, Operator): return self.operator == other.operator and self.lhs.Equals(
other.lhs) and self.rhs.Equals(other.rhs) returnFalse
def ToPerfJson(self): if self.rhs: return f'{self.fn}({self.lhs.ToPerfJson()}, {self.rhs.ToPerfJson()})' return f'{self.fn}({self.lhs.ToPerfJson()})'
def ToPython(self): if self.rhs: return f'{self.fn}({self.lhs.ToPython()}, {self.rhs.ToPython()})' return f'{self.fn}({self.lhs.ToPython()})'
def Simplify(self) -> Expression:
lhs = self.lhs.Simplify()
rhs = self.rhs.Simplify() if self.rhs elseNone if isinstance(lhs, Constant) and isinstance(rhs, Constant): if self.fn == 'd_ratio': if rhs.value == '0': return Constant(0)
Constant(ast.literal_eval(f'{lhs} / {rhs}')) return Constant(ast.literal_eval(f'{self.fn}({lhs}, {rhs})'))
return Function(self.fn, lhs, rhs)
def Equals(self, other: Expression) -> bool: if isinstance(other, Function):
result = self.fn == other.fn and self.lhs.Equals(other.lhs) if self.rhs:
result = result and self.rhs.Equals(other.rhs) return result returnFalse
class Metric: """An individual metric that will specifiable on the perf command line."""
groups: Set[str]
expr: Expression
scale_unit: str
constraint: bool
def __init__(self,
name: str,
description: str,
expr: Expression,
scale_unit: str,
constraint: bool = False):
self.name = name
self.description = description
self.expr = expr.Simplify() # Workraound valid_only_metric hiding certain metrics based on unit.
scale_unit = scale_unit.replace('/sec', ' per sec') if scale_unit[0].isdigit():
self.scale_unit = scale_unit else:
self.scale_unit = f'1{scale_unit}'
self.constraint = constraint
self.groups = set()
Metric groups may be specificd on the perf command line, but within
the json they aren't encoded. Metrics may be in multiple groups
which can facilitate arrangements similar to trees. """
def __init__(self, name: str, metric_list: List[Union[Metric, 'MetricGroup']]):
self.name = name
self.metric_list = metric_list for metric in metric_list:
metric.AddToMetricGroup(self)
def AddToMetricGroup(self, group): """Callback used when a MetricGroup is added into another.""" for metric in self.metric_list:
metric.AddToMetricGroup(group)
def Flatten(self) -> Set[Metric]: """Returns a set of all leaf metrics."""
result = set() for x in self.metric_list:
result = result.union(x.Flatten())
Converts a json encoded metric expression by way of python's ast and
eval routine. First tokens are mapped to Event calls, then
accidentally converted keywords or literals are mapped to their
appropriate calls. Python's ast is used to match if-else that can't
be handled via operator overloading. Finally the ast is evaluated.
Args:
orig (str): String to parse.
Returns:
Expression: The parsed string. """ # pylint: disable=eval-used
py = orig.strip() # First try to convert everything that looks like a string (event name) into Event(r"EVENT_NAME"). # This isn't very selective so is followed up by converting some unwanted conversions back again
py = re.sub(r'([a-zA-Z][^-+/\* \\\(\),]*(?:\\.[^-+/\* \\\(\),]*)*)',
r'Event(r"\1")', py) # If it started with a # it should have been a literal, rather than an event name
py = re.sub(r'#Event\(r"([^"]*)"\)', r'Literal("#\1")', py) # Convert accidentally converted hex constants ("0Event(r"xDEADBEEF)"") back to a constant, # but keep it wrapped in Event(), otherwise Python drops the 0x prefix and it gets interpreted as # a double by the Bison parser
py = re.sub(r'0Event\(r"[xX]([0-9a-fA-F]*)"\)', r'Event("0x\1")', py) # Convert accidentally converted scientific notation constants back
py = re.sub(r'([0-9]+)Event\(r"(e[0-9]+)"\)', r'\1\2', py) # Convert all the known keywords back from events to just the keyword
keywords = ['if', 'else', 'min', 'max', 'd_ratio', 'source_count', 'has_event', 'strcmp_cpuid_str'] for kw in keywords:
py = re.sub(rf'Event\(r"{kw}"\)', kw, py) try:
parsed = ast.parse(py, mode='eval') except SyntaxError as e: raise SyntaxError(f'Parsing expression:\n{orig}') from e
_RewriteIfExpToSelect().visit(parsed)
parsed = ast.fix_missing_locations(parsed) return _Constify(eval(compile(parsed, orig, 'eval')))
def RewriteMetricsInTermsOfOthers(metrics: List[Tuple[str, str, Expression]]
)-> Dict[Tuple[str, str], Expression]: """Shorten metrics by rewriting in terms of others.
Args:
metrics (list): pmus, metric names and their expressions.
Returns:
Dict: mapping from a pmu, metric name pair to a shortened expression. """
updates: Dict[Tuple[str, str], Expression] = dict() for outer_pmu, outer_name, outer_expression in metrics: if outer_pmu isNone:
outer_pmu = 'cpu'
updated = outer_expression whileTrue: for inner_pmu, inner_name, inner_expression in metrics: if inner_pmu isNone:
inner_pmu = 'cpu' if inner_pmu.lower() != outer_pmu.lower(): continue if inner_name.lower() == outer_name.lower(): continue if (inner_pmu, inner_name) in updates:
inner_expression = updates[(inner_pmu, inner_name)]
updated = updated.Substitute(inner_name, inner_expression) if updated.Equals(outer_expression): break if (outer_pmu, outer_name) in updates and updated.Equals(updates[(outer_pmu, outer_name)]): break
updates[(outer_pmu, outer_name)] = updated return updates
Messung V0.5
¤ Dauer der Verarbeitung: 0.12 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.