Home | History | Annotate | Line # | Download | only in contrib
analyze_brprob.py revision 1.1
      1  1.1  mrg #!/usr/bin/env python3
      2  1.1  mrg #
      3  1.1  mrg # Script to analyze results of our branch prediction heuristics
      4  1.1  mrg #
      5  1.1  mrg # This file is part of GCC.
      6  1.1  mrg #
      7  1.1  mrg # GCC is free software; you can redistribute it and/or modify it under
      8  1.1  mrg # the terms of the GNU General Public License as published by the Free
      9  1.1  mrg # Software Foundation; either version 3, or (at your option) any later
     10  1.1  mrg # version.
     11  1.1  mrg #
     12  1.1  mrg # GCC is distributed in the hope that it will be useful, but WITHOUT ANY
     13  1.1  mrg # WARRANTY; without even the implied warranty of MERCHANTABILITY or
     14  1.1  mrg # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
     15  1.1  mrg # for more details.
     16  1.1  mrg #
     17  1.1  mrg # You should have received a copy of the GNU General Public License
     18  1.1  mrg # along with GCC; see the file COPYING3.  If not see
     19  1.1  mrg # <http://www.gnu.org/licenses/>.  */
     20  1.1  mrg #
     21  1.1  mrg #
     22  1.1  mrg #
     23  1.1  mrg # This script is used to calculate two basic properties of the branch prediction
     24  1.1  mrg # heuristics - coverage and hitrate.  Coverage is number of executions
     25  1.1  mrg # of a given branch matched by the heuristics and hitrate is probability
     26  1.1  mrg # that once branch is predicted as taken it is really taken.
     27  1.1  mrg #
     28  1.1  mrg # These values are useful to determine the quality of given heuristics.
     29  1.1  mrg # Hitrate may be directly used in predict.def.
     30  1.1  mrg #
     31  1.1  mrg # Usage:
     32  1.1  mrg #  Step 1: Compile and profile your program.  You need to use -fprofile-generate
     33  1.1  mrg #    flag to get the profiles.
     34  1.1  mrg #  Step 2: Make a reference run of the intrumented application.
     35  1.1  mrg #  Step 3: Compile the program with collected profile and dump IPA profiles
     36  1.1  mrg #          (-fprofile-use -fdump-ipa-profile-details)
     37  1.1  mrg #  Step 4: Collect all generated dump files:
     38  1.1  mrg #          find . -name '*.profile' | xargs cat > dump_file
     39  1.1  mrg #  Step 5: Run the script:
     40  1.1  mrg #          ./analyze_brprob.py dump_file
     41  1.1  mrg #          and read results.  Basically the following table is printed:
     42  1.1  mrg #
     43  1.1  mrg # HEURISTICS                           BRANCHES  (REL)  HITRATE                COVERAGE  (REL)
     44  1.1  mrg # early return (on trees)                     3   0.2%  35.83% /  93.64%          66360   0.0%
     45  1.1  mrg # guess loop iv compare                       8   0.6%  53.35% /  53.73%       11183344   0.0%
     46  1.1  mrg # call                                       18   1.4%  31.95% /  69.95%       51880179   0.2%
     47  1.1  mrg # loop guard                                 23   1.8%  84.13% /  84.85%    13749065956  42.2%
     48  1.1  mrg # opcode values positive (on trees)          42   3.3%  15.71% /  84.81%     6771097902  20.8%
     49  1.1  mrg # opcode values nonequal (on trees)         226  17.6%  72.48% /  72.84%      844753864   2.6%
     50  1.1  mrg # loop exit                                 231  18.0%  86.97% /  86.98%     8952666897  27.5%
     51  1.1  mrg # loop iterations                           239  18.6%  91.10% /  91.10%     3062707264   9.4%
     52  1.1  mrg # DS theory                                 281  21.9%  82.08% /  83.39%     7787264075  23.9%
     53  1.1  mrg # no prediction                             293  22.9%  46.92% /  70.70%     2293267840   7.0%
     54  1.1  mrg # guessed loop iterations                   313  24.4%  76.41% /  76.41%    10782750177  33.1%
     55  1.1  mrg # first match                               708  55.2%  82.30% /  82.31%    22489588691  69.0%
     56  1.1  mrg # combined                                 1282 100.0%  79.76% /  81.75%    32570120606 100.0%
     57  1.1  mrg #
     58  1.1  mrg #
     59  1.1  mrg #  The heuristics called "first match" is a heuristics used by GCC branch
     60  1.1  mrg #  prediction pass and it predicts 55.2% branches correctly. As you can,
     61  1.1  mrg #  the heuristics has very good covertage (69.05%).  On the other hand,
     62  1.1  mrg #  "opcode values nonequal (on trees)" heuristics has good hirate, but poor
     63  1.1  mrg #  coverage.
     64  1.1  mrg 
     65  1.1  mrg import sys
     66  1.1  mrg import os
     67  1.1  mrg import re
     68  1.1  mrg import argparse
     69  1.1  mrg 
     70  1.1  mrg from math import *
     71  1.1  mrg 
     72  1.1  mrg counter_aggregates = set(['combined', 'first match', 'DS theory',
     73  1.1  mrg     'no prediction'])
     74  1.1  mrg 
     75  1.1  mrg def percentage(a, b):
     76  1.1  mrg     return 100.0 * a / b
     77  1.1  mrg 
     78  1.1  mrg def average(values):
     79  1.1  mrg     return 1.0 * sum(values) / len(values)
     80  1.1  mrg 
     81  1.1  mrg def average_cutoff(values, cut):
     82  1.1  mrg     l = len(values)
     83  1.1  mrg     skip = floor(l * cut / 2)
     84  1.1  mrg     if skip > 0:
     85  1.1  mrg         values.sort()
     86  1.1  mrg         values = values[skip:-skip]
     87  1.1  mrg     return average(values)
     88  1.1  mrg 
     89  1.1  mrg def median(values):
     90  1.1  mrg     values.sort()
     91  1.1  mrg     return values[int(len(values) / 2)]
     92  1.1  mrg 
     93  1.1  mrg class Summary:
     94  1.1  mrg     def __init__(self, name):
     95  1.1  mrg         self.name = name
     96  1.1  mrg         self.branches = 0
     97  1.1  mrg         self.successfull_branches = 0
     98  1.1  mrg         self.count = 0
     99  1.1  mrg         self.hits = 0
    100  1.1  mrg         self.fits = 0
    101  1.1  mrg 
    102  1.1  mrg     def get_hitrate(self):
    103  1.1  mrg         return 100.0 * self.hits / self.count
    104  1.1  mrg 
    105  1.1  mrg     def get_branch_hitrate(self):
    106  1.1  mrg         return 100.0 * self.successfull_branches / self.branches
    107  1.1  mrg 
    108  1.1  mrg     def count_formatted(self):
    109  1.1  mrg         v = self.count
    110  1.1  mrg         for unit in ['','K','M','G','T','P','E','Z']:
    111  1.1  mrg             if v < 1000:
    112  1.1  mrg                 return "%3.2f%s" % (v, unit)
    113  1.1  mrg             v /= 1000.0
    114  1.1  mrg         return "%.1f%s" % (v, 'Y')
    115  1.1  mrg 
    116  1.1  mrg     def print(self, branches_max, count_max):
    117  1.1  mrg         print('%-40s %8i %5.1f%% %11.2f%% %7.2f%% / %6.2f%% %14i %8s %5.1f%%' %
    118  1.1  mrg             (self.name, self.branches,
    119  1.1  mrg                 percentage(self.branches, branches_max),
    120  1.1  mrg                 self.get_branch_hitrate(),
    121  1.1  mrg                 self.get_hitrate(),
    122  1.1  mrg                 percentage(self.fits, self.count),
    123  1.1  mrg                 self.count, self.count_formatted(),
    124  1.1  mrg                 percentage(self.count, count_max)))
    125  1.1  mrg 
    126  1.1  mrg class Profile:
    127  1.1  mrg     def __init__(self, filename):
    128  1.1  mrg         self.filename = filename
    129  1.1  mrg         self.heuristics = {}
    130  1.1  mrg         self.niter_vector = []
    131  1.1  mrg 
    132  1.1  mrg     def add(self, name, prediction, count, hits):
    133  1.1  mrg         if not name in self.heuristics:
    134  1.1  mrg             self.heuristics[name] = Summary(name)
    135  1.1  mrg 
    136  1.1  mrg         s = self.heuristics[name]
    137  1.1  mrg         s.branches += 1
    138  1.1  mrg 
    139  1.1  mrg         s.count += count
    140  1.1  mrg         if prediction < 50:
    141  1.1  mrg             hits = count - hits
    142  1.1  mrg         remaining = count - hits
    143  1.1  mrg         if hits >= remaining:
    144  1.1  mrg             s.successfull_branches += 1
    145  1.1  mrg 
    146  1.1  mrg         s.hits += hits
    147  1.1  mrg         s.fits += max(hits, remaining)
    148  1.1  mrg 
    149  1.1  mrg     def add_loop_niter(self, niter):
    150  1.1  mrg         if niter > 0:
    151  1.1  mrg             self.niter_vector.append(niter)
    152  1.1  mrg 
    153  1.1  mrg     def branches_max(self):
    154  1.1  mrg         return max([v.branches for k, v in self.heuristics.items()])
    155  1.1  mrg 
    156  1.1  mrg     def count_max(self):
    157  1.1  mrg         return max([v.count for k, v in self.heuristics.items()])
    158  1.1  mrg 
    159  1.1  mrg     def print_group(self, sorting, group_name, heuristics):
    160  1.1  mrg         count_max = self.count_max()
    161  1.1  mrg         branches_max = self.branches_max()
    162  1.1  mrg 
    163  1.1  mrg         sorter = lambda x: x.branches
    164  1.1  mrg         if sorting == 'branch-hitrate':
    165  1.1  mrg             sorter = lambda x: x.get_branch_hitrate()
    166  1.1  mrg         elif sorting == 'hitrate':
    167  1.1  mrg             sorter = lambda x: x.get_hitrate()
    168  1.1  mrg         elif sorting == 'coverage':
    169  1.1  mrg             sorter = lambda x: x.count
    170  1.1  mrg         elif sorting == 'name':
    171  1.1  mrg             sorter = lambda x: x.name.lower()
    172  1.1  mrg 
    173  1.1  mrg         print('%-40s %8s %6s %12s %18s %14s %8s %6s' %
    174  1.1  mrg             ('HEURISTICS', 'BRANCHES', '(REL)',
    175  1.1  mrg             'BR. HITRATE', 'HITRATE', 'COVERAGE', 'COVERAGE', '(REL)'))
    176  1.1  mrg         for h in sorted(heuristics, key = sorter):
    177  1.1  mrg             h.print(branches_max, count_max)
    178  1.1  mrg 
    179  1.1  mrg     def dump(self, sorting):
    180  1.1  mrg         heuristics = self.heuristics.values()
    181  1.1  mrg         if len(heuristics) == 0:
    182  1.1  mrg             print('No heuristics available')
    183  1.1  mrg             return
    184  1.1  mrg 
    185  1.1  mrg         special = list(filter(lambda x: x.name in counter_aggregates,
    186  1.1  mrg             heuristics))
    187  1.1  mrg         normal = list(filter(lambda x: x.name not in counter_aggregates,
    188  1.1  mrg             heuristics))
    189  1.1  mrg 
    190  1.1  mrg         self.print_group(sorting, 'HEURISTICS', normal)
    191  1.1  mrg         print()
    192  1.1  mrg         self.print_group(sorting, 'HEURISTIC AGGREGATES', special)
    193  1.1  mrg 
    194  1.1  mrg         if len(self.niter_vector) > 0:
    195  1.1  mrg             print ('\nLoop count: %d' % len(self.niter_vector)),
    196  1.1  mrg             print('  avg. # of iter: %.2f' % average(self.niter_vector))
    197  1.1  mrg             print('  median # of iter: %.2f' % median(self.niter_vector))
    198  1.1  mrg             for v in [1, 5, 10, 20, 30]:
    199  1.1  mrg                 cut = 0.01 * v
    200  1.1  mrg                 print('  avg. (%d%% cutoff) # of iter: %.2f'
    201  1.1  mrg                     % (v, average_cutoff(self.niter_vector, cut)))
    202  1.1  mrg 
    203  1.1  mrg parser = argparse.ArgumentParser()
    204  1.1  mrg parser.add_argument('dump_file', metavar = 'dump_file',
    205  1.1  mrg     help = 'IPA profile dump file')
    206  1.1  mrg parser.add_argument('-s', '--sorting', dest = 'sorting',
    207  1.1  mrg     choices = ['branches', 'branch-hitrate', 'hitrate', 'coverage', 'name'],
    208  1.1  mrg     default = 'branches')
    209  1.1  mrg 
    210  1.1  mrg args = parser.parse_args()
    211  1.1  mrg 
    212  1.1  mrg profile = Profile(sys.argv[1])
    213  1.1  mrg r = re.compile('  (.*) heuristics( of edge [0-9]*->[0-9]*)?( \\(.*\\))?: (.*)%.*exec ([0-9]*) hit ([0-9]*)')
    214  1.1  mrg loop_niter_str = ';;  profile-based iteration count: '
    215  1.1  mrg for l in open(args.dump_file).readlines():
    216  1.1  mrg     m = r.match(l)
    217  1.1  mrg     if m != None and m.group(3) == None:
    218  1.1  mrg         name = m.group(1)
    219  1.1  mrg         prediction = float(m.group(4))
    220  1.1  mrg         count = int(m.group(5))
    221  1.1  mrg         hits = int(m.group(6))
    222  1.1  mrg 
    223  1.1  mrg         profile.add(name, prediction, count, hits)
    224  1.1  mrg     elif l.startswith(loop_niter_str):
    225  1.1  mrg         v = int(l[len(loop_niter_str):])
    226  1.1  mrg         profile.add_loop_niter(v)
    227  1.1  mrg 
    228  1.1  mrg profile.dump(args.sorting)
    229