aboutsummaryrefslogtreecommitdiffstats
path: root/library/python/import_tracing/lib/converters/raw.py
blob: 7c307a5984a7bcb896aa7ae5594392e0ee7476ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import library.python.import_tracing.lib.converters.base as base_converter
import library.python.import_tracing.lib.constants as constants


class RawTextTraceConverter(base_converter.BaseTraceConverter):
    @staticmethod
    def _get_columns_length(events):
        max_filename = 0
        max_cumtime = 0
        max_end_time = 0

        for event in events:
            max_filename = max(max_filename, len(event.filename))
            max_cumtime = max(max_cumtime, event.end_time - event.start_time)
            max_end_time = max(max_end_time, event.end_time)

        return len(str(max_cumtime)), max_filename, max_end_time

    @staticmethod
    def _get_sorted_events(events):
        return sorted(events, key=lambda event: event.end_time - event.start_time, reverse=True)

    @staticmethod
    def _format_line(cumtime, filename, max_cumtime, max_filename):
        return "{0:<{max_cumtime}}\t{1:<{max_filename}}\n".format(
            cumtime,
            filename,
            max_cumtime=max_cumtime,
            max_filename=max_filename,
        )

    def dump(self, events, filepath):
        max_cumtime, max_filename, max_end_time = self._get_columns_length(events)
        max_line_length = max_cumtime + max_filename

        with open(filepath, "w") as file:
            # total time taken
            file.write("total time taken (seconds): {0:.4f}\n".format(max_end_time / constants.MCS_IN_SEC))
            file.write("-" * max_line_length + "\n")

            # header
            file.write(self._format_line("cumtime", "filename", max_cumtime, max_filename))
            file.write("-" * max_line_length + "\n")

            # trace info
            for event in self._get_sorted_events(events):
                time_taken = format(((event.end_time - event.start_time) / constants.MCS_IN_SEC), ".6f")

                file.write(
                    self._format_line(
                        time_taken,
                        event.filename,
                        max_cumtime,
                        max_filename,
                    )
                )