File size: 8,302 Bytes
34292e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env python3

# This scripts attempts to generate elasped time in seconds for all the steps
# in the flow and prints it in a table
# ---------------------------------------------------------------------------

import argparse
import hashlib
import pathlib
import os
import re
import sys

# Parse and validate arguments
# ==============================================================================


# Primary data artifacts first, then derived/exported artifacts and
# the SDC constraint file: yosys emits .v / .rtlil; OpenROAD stages
# emit .odb (and often .def / .sdc); routing emits .spef; finish
# emits .gds.
RESULT_EXTS = [".v", ".rtlil", ".odb", ".def", ".spef", ".gds", ".sdc"]


# The timing line run_command.py emits, matched wherever it appears in
# the line rather than from its start.  A RUN_CMD wrapper is free to
# prefix every log line -- a per-line elapsed stamp, "[  123.45] " --
# and such a prefix must not change what this reports.  Hours are
# optional, as _format_elapsed only emits them past an hour, and the
# fraction of a second is matched so it can be discarded from the
# reported seconds, but kept for the CPU/elapsed ratio.
ELAPSED_RE = re.compile(r"Elapsed time: (?:(\d+):)?(\d+):(\d+)(\.\d+)?\[h:\]min:sec")

# The CPU time run_command.py emits on the same line, as user and sys
# seconds; reported as their sum.
CPU_RE = re.compile(r"CPU time: user (\d+(?:\.\d+)?) sys (\d+(?:\.\d+)?)")


def get_hashes(f):
    """Return [(ext, sha1), ...] for every result file alongside log
    `f` whose extension is in RESULT_EXTS.  A yosys stage typically
    produces both `.v` and `.sdc`; a floorplan/route stage produces
    `.odb` (and often `.sdc`); the canonicalize stage produces
    `.rtlil`.  Hashing each separately makes "the netlist changed"
    distinguishable from "the SDC changed" in the elapsed-time table
    used to triage divergent local vs CI builds.

    Falls back to a single ("", "N/A") entry when no result file
    exists so the caller always emits at least one row per stage.
    """
    results = []
    for ext in RESULT_EXTS:
        result_file = pathlib.Path(
            str(f).replace("logs/", "results/").replace(".log", ext)
        )
        if result_file.exists():
            hasher = hashlib.sha1()
            with open(result_file, "rb") as rf:
                while True:
                    chunk = rf.read(16 * 1024 * 1024)
                    if not chunk:
                        break
                    hasher.update(chunk)
            results.append((ext, hasher.hexdigest()))
    if not results:
        results.append(("", "N/A"))
    return results


def print_log_dir_times(logdir, args):
    first = True
    totalElapsed = 0
    totalCpu = 0.0
    # Elapsed time of only the steps that report CPU time, so the total
    # CPU/elapsed ratio isn't diluted by steps without it.
    totalCpuElapsed = 0.0
    total_max_memory = 0
    if not args.match:
        print(logdir)

    # Loop on all log files in the directory
    for f in sorted(pathlib.Path(logdir).glob("**/*.log")):
        # kepler-formal's own logs; its timing is in ${step}_lec/_sec.log
        if any(x in str(f) for x in ["eqy_output", "_lec_check", "_sec_check"]):
            continue
        # Extract Elapsed Time line from log file
        stem = os.path.splitext(os.path.basename(str(f)))[0]
        if args.match and args.match != stem:
            continue
        with open(str(f)) as logfile:
            found = False
            for line in logfile:
                elapsedTime = None
                elapsedFraction = 0.0
                cpuTime = None
                peak_memory = None

                # Example line:
                # Elapsed time: 0:04.26[h:]min:sec. CPU time: user 4.08 sys 0.17 (99%). Peak memory: 671508KB.
                if "Elapsed time" in line:
                    found = True
                    # Match the 'h:m:s' time against the known format,
                    # so anything the line is prefixed with is ignored.
                    timeMatch = ELAPSED_RE.search(line)
                    if timeMatch:
                        hours, minutes, seconds, fraction = timeMatch.groups()
                        # Any fraction of a second is dropped.
                        if fraction:
                            elapsedFraction = float(fraction)
                        elapsedTime = int(minutes) * 60 + int(seconds)
                        if hours is not None:
                            elapsedTime += int(hours) * 3600
                    else:
                        print(
                            "Elapsed time not understood in", str(line), file=sys.stderr
                        )
                    cpuMatch = CPU_RE.search(line)
                    if cpuMatch:
                        cpuTime = float(cpuMatch.group(1)) + float(cpuMatch.group(2))
                    # Find Peak Memory
                    peak_memory = int(
                        int(line.split("Peak memory: ")[1].split("KB")[0]) / 1024
                    )
                    break

            hashes = get_hashes(f)

            if not found:
                print("No elapsed time found in", str(f), file=sys.stderr)
                continue

        # Print the name of the step and the corresponding elapsed time.
        # One row per (stage, result-file-ext); only the first row of a
        # stage shows elapsed/cpu/peak.
        if elapsedTime is not None and peak_memory is not None:
            if first and not args.noHeader:
                print_header()
                first = False
            stage_first = True
            for ext, h in hashes:
                if stage_first:
                    if cpuTime is None:
                        cpu = "N/A"
                    else:
                        cpu = round(cpuTime)
                    ratio = cpu_ratio(cpuTime, elapsedTime + elapsedFraction)
                    print_row(stem, ext, elapsedTime, cpu, ratio, peak_memory, h[0:10])
                else:
                    print_row(stem, ext, "", "", "", "", h[0:10])
                stage_first = False
        # LEC/SEC run inside another step (e.g. 6_report), which already
        # counts their time.
        nested = stem.endswith(("_lec", "_sec"))
        if elapsedTime is not None and not nested:
            totalElapsed += elapsedTime
        if cpuTime is not None and elapsedTime is not None and not nested:
            totalCpu += cpuTime
            totalCpuElapsed += elapsedTime + elapsedFraction
        if peak_memory is not None:
            total_max_memory = max(total_max_memory, int(peak_memory))

    if totalElapsed != 0 and not args.match:
        print_row(
            "Total",
            "",
            totalElapsed,
            round(totalCpu),
            cpu_ratio(totalCpu, totalCpuElapsed),
            total_max_memory,
            "",
        )


def cpu_ratio(cpu, elapsed):
    """CPU time over elapsed time: roughly the number of busy threads."""
    if cpu is None or not elapsed:
        return "N/A"
    return "%.2f" % (cpu / elapsed)


def print_header():
    """Print the column headers, split over two lines to keep the
    columns narrow."""
    print_row("Log", "Ext", "Elapsed", "CPU", "CPU/", "Peak Mem", "sha1sum")
    print_row("", "", "s", "s", "Elapsed", "MB", "[0:10)")


def print_row(log, ext, elapsed, cpu, ratio, memory, sha):
    fmt = "%-22s %-6s %8s %8s %8s %8s %s"
    row = fmt % (log, ext, elapsed, cpu, ratio, memory, sha)
    print(row.rstrip())


def scan_logs(args):
    parser = argparse.ArgumentParser(
        description="Print elapsed time for every step in the flow"
    )
    parser.add_argument(
        "--match",
        help="Match this string in the log file names",
    )
    parser.add_argument(
        "--logDir", "-d", required=True, nargs="+", help="Log files directories"
    )
    parser.add_argument("--noHeader", action="store_true", help="Skip the header")
    args = parser.parse_args(args)

    if not args.logDir:
        print("[ERROR] Please add a logDir" "-d/--logDir.", file=sys.stderr)
        parser.print_help()
        sys.exit(1)

    for log_dir in args.logDir:
        print_log_dir_times(log_dir, args)


if __name__ == "__main__":
    scan_logs(sys.argv[1:])