Lit: Resurrect --no-execute dropped in r187852.
[oota-llvm.git] / utils / lit / lit / Util.py
1 import os, sys
2
3 def detectCPUs():
4     """
5     Detects the number of CPUs on a system. Cribbed from pp.
6     """
7     # Linux, Unix and MacOS:
8     if hasattr(os, "sysconf"):
9         if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
10             # Linux & Unix:
11             ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
12             if isinstance(ncpus, int) and ncpus > 0:
13                 return ncpus
14         else: # OSX:
15             return int(capture(['sysctl', '-n', 'hw.ncpu']))
16     # Windows:
17     if os.environ.has_key("NUMBER_OF_PROCESSORS"):
18         ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
19         if ncpus > 0:
20             return ncpus
21     return 1 # Default
22
23 def mkdir_p(path):
24     """mkdir_p(path) - Make the "path" directory, if it does not exist; this
25     will also make directories for any missing parent directories."""
26     import errno
27
28     if not path or os.path.exists(path):
29         return
30
31     parent = os.path.dirname(path) 
32     if parent != path:
33         mkdir_p(parent)
34
35     try:
36         os.mkdir(path)
37     except OSError:
38         e = sys.exc_info()[1]
39         # Ignore EEXIST, which may occur during a race condition.
40         if e.errno != errno.EEXIST:
41             raise
42
43 def capture(args, env=None):
44     import subprocess
45     """capture(command) - Run the given command (or argv list) in a shell and
46     return the standard output."""
47     p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
48                          env=env)
49     out,_ = p.communicate()
50     return out
51
52 def which(command, paths = None):
53     """which(command, [paths]) - Look up the given command in the paths string
54     (or the PATH environment variable, if unspecified)."""
55
56     if paths is None:
57         paths = os.environ.get('PATH','')
58
59     # Check for absolute match first.
60     if os.path.isfile(command):
61         return command
62
63     # Would be nice if Python had a lib function for this.
64     if not paths:
65         paths = os.defpath
66
67     # Get suffixes to search.
68     # On Cygwin, 'PATHEXT' may exist but it should not be used.
69     if os.pathsep == ';':
70         pathext = os.environ.get('PATHEXT', '').split(';')
71     else:
72         pathext = ['']
73
74     # Search the paths...
75     for path in paths.split(os.pathsep):
76         for ext in pathext:
77             p = os.path.join(path, command + ext)
78             if os.path.exists(p):
79                 return p
80
81     return None
82
83 def checkToolsPath(dir, tools):
84     for tool in tools:
85         if not os.path.exists(os.path.join(dir, tool)):
86             return False;
87     return True;
88
89 def whichTools(tools, paths):
90     for path in paths.split(os.pathsep):
91         if checkToolsPath(path, tools):
92             return path
93     return None
94
95 def printHistogram(items, title = 'Items'):
96     import itertools, math
97
98     items.sort(key = lambda item: item[1])
99
100     maxValue = max([v for _,v in items])
101
102     # Select first "nice" bar height that produces more than 10 bars.
103     power = int(math.ceil(math.log(maxValue, 10)))
104     for inc in itertools.cycle((5, 2, 2.5, 1)):
105         barH = inc * 10**power
106         N = int(math.ceil(maxValue / barH))
107         if N > 10:
108             break
109         elif inc == 1:
110             power -= 1
111
112     histo = [set() for i in range(N)]
113     for name,v in items:
114         bin = min(int(N * v/maxValue), N-1)
115         histo[bin].add(name)
116
117     barW = 40
118     hr = '-' * (barW + 34)
119     print('\nSlowest %s:' % title)
120     print(hr)
121     for name,value in items[-20:]:
122         print('%.2fs: %s' % (value, name))
123     print('\n%s Times:' % title)
124     print(hr)
125     pDigits = int(math.ceil(math.log(maxValue, 10)))
126     pfDigits = max(0, 3-pDigits)
127     if pfDigits:
128         pDigits += pfDigits + 1
129     cDigits = int(math.ceil(math.log(len(items), 10)))
130     print("[%s] :: [%s] :: [%s]" % ('Range'.center((pDigits+1)*2 + 3),
131                                     'Percentage'.center(barW),
132                                     'Count'.center(cDigits*2 + 1)))
133     print(hr)
134     for i,row in enumerate(histo):
135         pct = float(len(row)) / len(items)
136         w = int(barW * pct)
137         print("[%*.*fs,%*.*fs) :: [%s%s] :: [%*d/%*d]" % (
138             pDigits, pfDigits, i*barH, pDigits, pfDigits, (i+1)*barH,
139             '*'*w, ' '*(barW-w), cDigits, len(row), cDigits, len(items)))
140