分享5個python提速技巧,速度瞬間提上來瞭
1、跳過迭代對象的開頭
string_from_file = """ // Wooden: ... // LaoLi: ... // // Whole: ... Wooden LaoLi... """ import itertools for line in itertools.dropwhile(lambda line: line.startswith("//"), string_from_file.split(" ")): print(line)
2、避免數據復制
# 不推薦寫法,代碼耗時:6.5秒 def main(): size = 10000 for _ in range(size): value = range(size) value_list = [x for x in value] square_list = [x * x for x in value_list] main()
# 推薦寫法,代碼耗時:4.8秒 def main(): size = 10000 for _ in range(size): value = range(size) square_list = [x * x for x in value] # 避免無意義的復制
3、避免變量中間變量
# 不推薦寫法,代碼耗時:0.07秒 def main(): size = 1000000 for _ in range(size): a = 3 b = 5 temp = a a = b b = temp main()
# 推薦寫法,代碼耗時:0.06秒 def main(): size = 1000000 for _ in range(size): a = 3 b = 5 a, b = b, a # 不借助中間變量 main()
4、循環優化
# 不推薦寫法。代碼耗時:6.7秒 def computeSum(size: int) -> int: sum_ = 0 i = 0 while i < size: sum_ += i i += 1 return sum_ def main(): size = 10000 for _ in range(size): sum_ = computeSum(size) main()
# 推薦寫法。代碼耗時:4.3秒 def computeSum(size: int) -> int: sum_ = 0 for i in range(size): # for 循環代替 while 循環 sum_ += i return sum_ def main(): size = 10000 for _ in range(size): sum_ = computeSum(size) main()
隱式for循環代替顯式for循環
# 推薦寫法。代碼耗時:1.7秒 def computeSum(size: int) -> int: return sum(range(size)) # 隱式 for 循環代替顯式 for 循環 def main(): size = 10000 for _ in range(size): sum = computeSum(size) main()
5、使用numba.jit
# 推薦寫法。代碼耗時:0.62秒 # numba可以將 Python 函數 JIT 編譯為機器碼執行,大大提高代碼運行速度。 import numba @numba.jit def computeSum(size: float) -> int: sum = 0 for i in range(size): sum += i return sum def main(): size = 10000 for _ in range(size): sum = computeSum(size) main()
到此這篇關於分享5個python提速技巧,速度瞬間提上來瞭的文章就介紹到這瞭,更多相關python提速技巧內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- numba提升python運行速度的實例方法
- 利用Numba與Cython結合提升python運行效率詳解
- 分享介紹Python的9個實用技巧
- 隻需要這一行代碼就能讓python計算速度提高十倍
- Python實現GPU加速的基本操作