開始使用免費開始

迴圈的速度

當然,set 比較適合用來搜尋元素。它是以雜湊為基礎,所以大多數時候你可以期待時間複雜度接近常數。不過,若要逐一走訪(iterate)物件裡的所有元素呢?讓我們用 pytestpytest-benchmark 比較在 listset 上進行迴圈走訪的速度。pytest 套件已經匯入。

本練習屬於課程

Python 測試入門

檢視課程

練習說明

  • 在所有以 iterate_ 開頭的函式前加上 @benchmark 修飾器。
  • 完成 iterate_listiterate_set 中的迴圈。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def test_list(benchmark):
	# Add decorator here
    @____
    def iterate_list():
		# Complete the loop here
        ____ in [i for i in range(1000)]:
            pass

def test_set(benchmark):
	# Add decorator here
    ____
    def iterate_set():
        # Complete the loop here
        ____ in {i for i in range(1000)}:
            pass
編輯並執行程式碼