1#!/usr/bin/env python3
2#
3#   Copyright 2020 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16
17from datetime import datetime
18
19
20class PerformanceTestLogger(object):
21    """
22    A helper class to log time points and intervals
23    """
24
25    def __init__(self):
26        self.base_timepoint = datetime.now()
27        # We use a dictionary of a list of timepoints
28        self.start_interval_points = {}
29        self.end_interval_points = {}
30        self.single_points = {}
31
32    def log_single_point(self, label=""):
33        if label not in self.single_points:
34            self.single_points[label] = []
35        self.single_points[label].append(datetime.now())
36
37    def start_interval(self, label=""):
38        if label not in self.start_interval_points:
39            self.start_interval_points[label] = []
40        self.start_interval_points[label].append(datetime.now())
41
42    def end_interval(self, label=""):
43        if label not in self.end_interval_points:
44            self.end_interval_points[label] = []
45        self.end_interval_points[label].append(datetime.now())
46
47    def _check_interval_label(self, label):
48        if label not in self.start_interval_points or label not in self.end_interval_points:
49            raise KeyError("label %s doesn't exist" % label)
50        if len(self.start_interval_points[label]) != len(self.end_interval_points[label]):
51            raise KeyError("label %s doesn't have correct start and end log" % label)
52
53    def get_duration_of_intervals(self, label):
54        """
55        Return the list of duration of the intervals with specified label.
56        """
57        self._check_interval_label(label)
58        intervals = []
59        for i in range(len(self.start_interval_points[label])):
60            interval = self.end_interval_points[label][i] - self.start_interval_points[label][i]
61            intervals.append(interval)
62        return intervals
63
64    def dump_intervals(self):
65        """
66        Gives an iterator of (iterator of label, start, end) over all labels
67        """
68        for label in self.start_interval_points:
69            self._check_interval_label(label)
70            yield ((label, self.start_interval_points[label][i], self.end_interval_points[label][i])
71                   for i in range(len(self.start_interval_points[label])))
72