加速Python列表和字典,讓你代碼更加高效
今天,我們將討論Python中的優(yōu)化技術(shù)。在本文中,您將了解如何通過避免在列表和字典中進(jìn)行重新計算來加快代碼的速度。
我們先編寫一個裝飾器函數(shù)來計算函數(shù)的執(zhí)行時間,方便測驗不同代碼的速度:
- import functools
- import time
- def timeit(func):
- @functools.wraps(func)
- def newfunc(*args, **kwargs):
- startTime = time.time()
- func(*args, **kwargs)
- elapsedTime = time.time() - startTime
- print('function - {}, took {} ms to complete'.format(func.__name__, int(elapsedTime * 1000)))
- return newfunc
一、避免在列表中重新評估
1. 在循環(huán)內(nèi)
代碼:
- @timeit
- def append_inside_loop(limit):
- nums = []
- for num in limit:
- nums.append(num)
- append_inside_loop(list(range(1, 9999999)))
在上面的函數(shù)中.append每次通過循環(huán)重新計算的函數(shù)引用。執(zhí)行后,上述函數(shù)所花費的總時間:
- o/p - function - append_inside_loop, took 529 ms to complete
2. 在循環(huán)外
代碼:
- @timeit
- def append_outside_loop(limit):
- nums = []
- append = nums.append
- for num in limit:
- append(num)
- append_outside_loop(list(range(1, 9999999)))
在上面的函數(shù)中,我們對nums.append在循環(huán)外部估值,并在循環(huán)內(nèi)部使用append為變量。總時間:
- o/p - function - append_outside_loop, took 328 ms to complete
如您所見,當(dāng)我們在for循環(huán)外部追加為一個本地變量,這將花費更少的時間,可以將代碼加速201 ms。
二、避免在字典中重新求值
1. 在循環(huán)內(nèi)部
代碼:
- @timeit
- def inside_evaluation(limit):
- data = {}
- for num in limit:
- data[num] = data.get(num, 0) + 1
- inside_evaluation(list(range(1, 9999999)))
上述函數(shù)所花費的總時間:
- o/p - function - inside_evaluation, took 1400 ms to complete
2. 在循環(huán)外
代碼:
- @timeit
- def outside_evaluation(limit):
- data = {}
- get = data.get
- for num in limit:
- data[num] = get(num, 0) + 1
- outside_evaluation(list(range(1, 9999999)))
上述函數(shù)所花費的總時間:
- o/p - function - outside_evaluation, took 1189 ms to complete
如你所見,我們這里的代碼速度提高了211毫秒。
英文原文:https://dev.to/sharmapacific/speedup-python-list-and-dictionary-12kd