開始使用免費開始

測量時間 I

在投影片中,你看到如何載入並使用 time.time() 函式來評估執行一個基本數學運算所需的時間。

現在,你要用同樣的策略來比較兩種不同的方法,解一個類似的問題:計算從 1 到 100 萬(1,000,000)所有正整數的平方和。

和影片中一樣,你會比較兩種方法:一種是以暴力法逐一計算,另一種是較為數學化的解法。

formula 函式中,我們使用標準公式:

$$ \frac{N*(N+1)(2N+1)}{6} $$

其中 N=1,000,000。

brute_force 函式中,我們從 1 迴圈到 100 萬,逐一把每個數的平方加到結果裡。

本練習屬於課程

使用 pandas 撰寫高效程式碼

檢視課程

練習說明

  • 使用 formula() 函式計算問題的結果。
  • 印出使用 formula() 函式計算結果所需的時間。
  • 使用 brute_force() 函式計算問題的結果。
  • 印出使用 brute_force() 函式計算結果所需的時間。

動手互動練習

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

# Calculate the result of the problem using formula() and print the time required
N = 1000000
fm_start_time = ____
first_method = formula(N)
print("Time using formula: {} sec".format(time.time() - fm_start_time))

# Calculate the result of the problem using brute_force() and print the time required
sm_start_time = ____
second_method = ____(N)
print("Time using the brute force: {} sec".format(time.time() - sm_start_time))
編輯並執行程式碼