2024.7.8 ループ処理の計算速度
for文を制御するためのイテラブルが
1. 配列
2. リスト
の処理速度の差を比較する。更に、while文を用いた場合(つまり、イテラブルから全ての要素を取り出して終了、ではなく条件を満たしている間繰り返し実行)とも比較する。
code:loop1.py
import numpy as np
import time
t_array = np.linspace(0, 100, 100000000)
t_list = t for t in t_array
# 配列
x = 0
t1s = time.process_time()
for t in t_array:
x = x + 1
t1 = time.process_time() - t1s
print('array:', t1)
# リスト
x = 0
t2s = time.process_time()
for t in t_list:
x = x + 1
t2 = time.process_time() - t2s
print('list:', t1)
# while
x = 0
t3s = time.process_time()
while x <= 100000000:
x = x + 1
t3 = time.process_time() - t3s
print('while:', t3)
code:result.txt
array: 3.8236535000000007
list: 3.8236535000000007
while: 2.781456799999999
リストと配列の間に有意な差はない
whileの処理が高速である、イテラブルへのアクセスを行わず、単純な条件式で判定を行っているだけなので、当然である。
whileの例を、計算過程をリストに記録するよう改良。
code:loop2.py
import time
# while-1
x = 0
t3s = time.process_time()
while x <= 100000000:
x = x + 1
t3 = time.process_time() - t3s
print('while-1:', t3)
# while-2
x = 0
hist_x = []
t4s = time.process_time()
while x <= 100000000:
x = x + 1
hist_x.append(x)
t4 = time.process_time() - t4s
print('while-2:', t4)
code:result2.txt
while-1: 2.9293384000000002
while-2: 5.7769554
より多くの計算時間が必要であることがわかる。
以、総括すると、ループ処理の制御方法によって実行時間に差が生じることがわかった。ただ、ここでは1億回のループの結果この程度の差しか生じないとも考えられるので、目的に応じて使い分ける、という考え方でよい。
ループの上限回数を設定するような場合はfor文が適している。
計算が収束したら終了というような場合はwhile文が適している。