首先,您必须计算算法的实际时间复杂度。这可以通过timeit.timeit(实际挂起时间)或手动计算操作次数来完成。
这是一个冒泡排序算法的例子:
def bubble_sort(a):
not_sorted = True
operations = 0
while not_sorted:
not_sorted = False
for i in range(len(a)-1):
operations += 1
if a[i] > a[i+1]:
a[i], a[i+1] = a[i+1], a[i]
not_sorted = True
return operations
现在您可以为这个函数提供不同大小的数组,收集每次所需的操作数并制作图表。
import matplotlib.pyplot as plt
from random import sample
# assuming we are in Jupyter:
%matplotlib inline
ns = range(10, 1000, 10)
ops = []
for n in ns:
my_list = sample(range(n), n)
ops.append(bubble_sort(my_list))
plt.plot(ns, ops)
您甚至可以使用如下统计数据检查渐近线:
from statsmodels.formula.api import ols
import pandas as pd
df = pd.DataFrame(dict(n=ns, ops=ops))
model = ols('ops ~ n + I(n**2)', df)
model = model.fit()
plt.plot(ns, ops)
plt.plot(ns, model.predict())
要找到实际的挂钟时间,只需使用
from timeit import timeit
time = timeit('bubble_sort(a)', number=10, globals=globals())