自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

加速Python列表和字典,讓你代碼更加高效

開發(fā) 后端
今天,我們將討論Python中的優(yōu)化技術(shù)。在本文中,您將了解如何通過避免在列表和字典中進(jìn)行重新計算來加快代碼的速度。

今天,我們將討論Python中的優(yōu)化技術(shù)。在本文中,您將了解如何通過避免在列表和字典中進(jìn)行重新計算來加快代碼的速度。

我們先編寫一個裝飾器函數(shù)來計算函數(shù)的執(zhí)行時間,方便測驗不同代碼的速度:

  1. import functools 
  2. import time 
  3.  
  4. def timeit(func): 
  5.     @functools.wraps(func) 
  6.     def newfunc(*args, **kwargs): 
  7.         startTime = time.time() 
  8.         func(*args, **kwargs) 
  9.         elapsedTime = time.time() - startTime 
  10.         print('function - {}, took {} ms to complete'.format(func.__name__, int(elapsedTime * 1000))) 
  11.     return newfunc 

一、避免在列表中重新評估

1. 在循環(huán)內(nèi)

代碼:

  1. @timeit 
  2. def append_inside_loop(limit): 
  3.     nums = [] 
  4.     for num in limit: 
  5.         nums.append(num) 
  6.  
  7. append_inside_loop(list(range(1, 9999999))) 

在上面的函數(shù)中.append每次通過循環(huán)重新計算的函數(shù)引用。執(zhí)行后,上述函數(shù)所花費的總時間:

  1. o/p - function - append_inside_loop, took 529 ms to complete 

2. 在循環(huán)外

代碼:

  1. @timeit 
  2. def append_outside_loop(limit): 
  3.     nums = [] 
  4.     append = nums.append 
  5.     for num in limit: 
  6.         append(num) 
  7.  
  8. append_outside_loop(list(range(1, 9999999))) 

在上面的函數(shù)中,我們對nums.append在循環(huán)外部估值,并在循環(huán)內(nèi)部使用append為變量。總時間:

  1. o/p - function - append_outside_loop, took 328 ms to complete 

如您所見,當(dāng)我們在​for循環(huán)外部追加為一個本地變量,這將花費更少的時間,可以將代碼加速201 ms。​

二、避免在字典中重新求值

1. 在循環(huán)內(nèi)部

代碼:

  1. @timeit 
  2. def inside_evaluation(limit): 
  3.     data = {} 
  4.     for num in limit: 
  5.         data[num] = data.get(num, 0) + 1 
  6.  
  7. inside_evaluation(list(range(1, 9999999))) 

上述函數(shù)所花費的總時間:

  1. o/p - function - inside_evaluation, took 1400 ms to complete 

2. 在循環(huán)外

代碼:

  1. @timeit 
  2. def outside_evaluation(limit): 
  3.     data = {} 
  4.     get = data.get 
  5.     for num in limit: 
  6.         data[num] = get(num, 0) + 1 
  7.  
  8.  
  9. outside_evaluation(list(range(1, 9999999))) 

上述函數(shù)所花費的總時間:

  1. o/p - function - outside_evaluation, took 1189 ms to complete 

如你所見,我們這里的代碼速度提高了211毫秒。

英文原文:https://dev.to/sharmapacific/speedup-python-list-and-dictionary-12kd

責(zé)任編輯:趙寧寧 來源: 今日頭條
相關(guān)推薦

2020-05-21 08:53:12

Python技術(shù)代碼

2024-06-13 12:24:06

C++開發(fā)代碼

2010-05-20 18:27:10

IIS服務(wù)器

2010-09-09 16:39:24

2009-06-09 10:13:46

賬號設(shè)置網(wǎng)絡(luò)控制

2017-04-20 12:56:46

原型設(shè)計工具

2017-12-07 10:09:55

數(shù)據(jù)中心資產(chǎn)審計

2023-11-23 15:28:38

2015-10-27 10:12:26

數(shù)據(jù)中心高效數(shù)據(jù)中心

2023-07-25 16:14:51

Python技巧

2025-03-11 08:30:00

Pythonretrying代碼

2020-08-21 09:52:03

數(shù)據(jù)中心IT技術(shù)

2018-01-30 10:28:29

數(shù)據(jù)中心云計算公共云

2024-04-26 11:54:10

Pygments代碼Pytho

2013-03-25 09:41:20

PythonCython

2020-09-02 14:00:05

Python代碼腳本

2009-10-13 10:12:10

ScalaTestScala

2018-02-08 11:30:45

邊緣計算物聯(lián)網(wǎng)應(yīng)用
點贊
收藏

51CTO技術(shù)棧公眾號