算法探查器:
Profiling 通过统计指令或执行的时间来度量一个算法的性能
'''
algorithms.py
Algorithms configured for profiling
'''
def selectionSort(lyst, profiler):
i = 0
while i < len(lyst) - 1:
minIndex = i
j = i + 1
while j < len(lyst):
profiler.comparison()
if lyst[j] < lyst[minIndex]:
minIndex = j
j += 1
if minIndex != i:
swap(lyst, minIndex, i, profiler)
i += 1
def swap(lyst, i, j, profiler):
profiler.exchange()
temp = lyst[i]
lyst[i] = lyst[j]
lyst[j] = temp
'''
profiler.py
Example use:
from profiler import Profiler
from algorithms import selectionSort
p = Profiler()
p.test(selectionSort, size=15, comp=True, exch=True, trace=True)
'''
import time
import random
class Profiler(object):
def test(self, function, lyst=None, size=10, unique=True,
comp=True, exch=True, trace=False):
'''
function: the algorithm being profiled
target: the search target if profiling a search
lyst: allows the caller to use her list
size: the size of the list, 10 by default
unique: if True, list contains unique integers
comp: if True, count comparisons
exch: if True, count exchanges
trace: if True, print the list after each exchange
'''
self._comp = comp
self._exch = exch
self._trace = trace
if lyst != None:
self._lyst = lyst
elif unique:
self._lyst = [i for i in range(1, size+1)]
random.shuffle(self._lyst)
else:
self.lyst = []
for count in range(size):
self._lyst.append(random.randint(1, size))
self._exchCount = 0
self._cmpCount = 0
self._startClock()
function(self._lyst, self)
self._stopClock()
print(self)
def exchange(self):
if self._exch:
self._exchCount += 1
if self._trace:
print(self._lyst)
def comparison(self):
if self._comp:
self._cmpCount += 1
def _startClock(self):
self._start = time.time()
def _stopClock(self):
self._elapsedTime = round(time.time() - self._start, 3)
def __str__(self):
result = 'Problem size: '
result += str(len(self._lyst)) + '\n'
result += 'Elapsed time: '
result += str(self._elapsedTime) + '\n'
if self._comp:
result += 'Comparisons: '
result += str(self._cmpCount) + '\n'
if self._exch:
result += 'Exchanges: '
result += str(self._exchCount) + '\n'
return result
通常减少算法复杂度的阶的做法,比通过调整代码来增强其性能要好