d7d6d7f16320739a052794d112344d36b5a0c709
[oota-llvm.git] / utils / lit / lit / Util.py
1 import errno
2 import itertools
3 import math
4 import os
5 import subprocess
6 import sys
7
8 def detectCPUs():
9     """
10     Detects the number of CPUs on a system. Cribbed from pp.
11     """
12     # Linux, Unix and MacOS:
13     if hasattr(os, "sysconf"):
14         if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
15             # Linux & Unix:
16             ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
17             if isinstance(ncpus, int) and ncpus > 0:
18                 return ncpus
19         else: # OSX:
20             return int(capture(['sysctl', '-n', 'hw.ncpu']))
21     # Windows:
22     if "NUMBER_OF_PROCESSORS" in os.environ:
23         ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
24         if ncpus > 0:
25             return ncpus
26     return 1 # Default
27
28 def mkdir_p(path):
29     """mkdir_p(path) - Make the "path" directory, if it does not exist; this
30     will also make directories for any missing parent directories."""
31     if not path or os.path.exists(path):
32         return
33
34     parent = os.path.dirname(path) 
35     if parent != path:
36         mkdir_p(parent)
37
38     try:
39         os.mkdir(path)
40     except OSError:
41         e = sys.exc_info()[1]
42         # Ignore EEXIST, which may occur during a race condition.
43         if e.errno != errno.EEXIST:
44             raise
45
46 def capture(args, env=None):
47     """capture(command) - Run the given command (or argv list) in a shell and
48     return the standard output."""
49     p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
50                          env=env)
51     out,_ = p.communicate()
52     return out
53
54 def which(command, paths = None):
55     """which(command, [paths]) - Look up the given command in the paths string
56     (or the PATH environment variable, if unspecified)."""
57
58     if paths is None:
59         paths = os.environ.get('PATH','')
60
61     # Check for absolute match first.
62     if os.path.isfile(command):
63         return command
64
65     # Would be nice if Python had a lib function for this.
66     if not paths:
67         paths = os.defpath
68
69     # Get suffixes to search.
70     # On Cygwin, 'PATHEXT' may exist but it should not be used.
71     if os.pathsep == ';':
72         pathext = os.environ.get('PATHEXT', '').split(';')
73     else:
74         pathext = ['']
75
76     # Search the paths...
77     for path in paths.split(os.pathsep):
78         for ext in pathext:
79             p = os.path.join(path, command + ext)
80             if os.path.exists(p):
81                 return p
82
83     return None
84
85 def checkToolsPath(dir, tools):
86     for tool in tools:
87         if not os.path.exists(os.path.join(dir, tool)):
88             return False;
89     return True;
90
91 def whichTools(tools, paths):
92     for path in paths.split(os.pathsep):
93         if checkToolsPath(path, tools):
94             return path
95     return None
96
97 def printHistogram(items, title = 'Items'):
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