5 Detects the number of CPUs on a system. Cribbed from pp.
7 # Linux, Unix and MacOS:
8 if hasattr(os, "sysconf"):
9 if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
11 ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
12 if isinstance(ncpus, int) and ncpus > 0:
15 return int(os.popen2("sysctl -n hw.ncpu")[1].read())
17 if os.environ.has_key("NUMBER_OF_PROCESSORS"):
18 ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
24 """mkdir_p(path) - Make the "path" directory, if it does not exist; this
25 will also make directories for any missing parent directories."""
28 if not path or os.path.exists(path):
31 parent = os.path.dirname(path)
38 # Ignore EEXIST, which may occur during a race condition.
39 if e.errno != errno.EEXIST:
44 """capture(command) - Run the given command (or argv list) in a shell and
45 return the standard output."""
46 p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
47 out,_ = p.communicate()
50 def which(command, paths = None):
51 """which(command, [paths]) - Look up the given command in the paths string
52 (or the PATH environment variable, if unspecified)."""
55 paths = os.environ.get('PATH','')
57 # Check for absolute match first.
58 if os.path.exists(command):
61 # Would be nice if Python had a lib function for this.
65 # Get suffixes to search.
66 pathext = os.environ.get('PATHEXT', '').split(os.pathsep)
69 for path in paths.split(os.pathsep):
71 p = os.path.join(path, command + ext)
77 def printHistogram(items, title = 'Items'):
78 import itertools, math
80 items.sort(key = lambda (_,v): v)
82 maxValue = max([v for _,v in items])
84 # Select first "nice" bar height that produces more than 10 bars.
85 power = int(math.ceil(math.log(maxValue, 10)))
86 for inc in itertools.cycle((5, 2, 2.5, 1)):
87 barH = inc * 10**power
88 N = int(math.ceil(maxValue / barH))
94 histo = [set() for i in range(N)]
96 bin = min(int(N * v/maxValue), N-1)
100 hr = '-' * (barW + 34)
101 print '\nSlowest %s:' % title
103 for name,value in items[-20:]:
104 print '%.2fs: %s' % (value, name)
105 print '\n%s Times:' % title
107 pDigits = int(math.ceil(math.log(maxValue, 10)))
108 pfDigits = max(0, 3-pDigits)
110 pDigits += pfDigits + 1
111 cDigits = int(math.ceil(math.log(len(items), 10)))
112 print "[%s] :: [%s] :: [%s]" % ('Range'.center((pDigits+1)*2 + 3),
113 'Percentage'.center(barW),
114 'Count'.center(cDigits*2 + 1))
116 for i,row in enumerate(histo):
117 pct = float(len(row)) / len(items)
119 print "[%*.*fs,%*.*fs)" % (pDigits, pfDigits, i*barH,
120 pDigits, pfDigits, (i+1)*barH),
121 print ":: [%s%s] :: [%*d/%*d]" % ('*'*w, ' '*(barW-w),