1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
from timeit import Timer import matplotlib.pyplot as plt
def test1(): l = [] for i in range(1000): l = l + [i]
def test2(): l = [] for i in range(1000): l.append(i)
def test3(): l = [i for i in range(1000)]
def test4(): l = list(range(1000))
t1 = Timer("test1()", "from __main__ import test1")
t2 = Timer("test2()", "from __main__ import test2")
t3 = Timer("test3()", "from __main__ import test3")
t4 = Timer("test4()", "from __main__ import test4")
result = [t1.timeit(1000), t2.timeit(1000), t3.timeit(1000), t4.timeit(1000)] method = ["for+ '+'", "for + append", "list comprehension", "list + range"]
plt.bar(method, result, color='rgby')
for x,y in zip(method, result): plt.text(x, y, "%fs" % y)
plt.show()
|