LoginSignup
2
1

More than 1 year has passed since last update.

【Python】結局"i += 1"と" i = i + 1"どっちが速いの?

Posted at

概要

"i += 1"と"i = i + 1"の処理速度を比較します。
すでに[小ネタ] Pythonでは、 i+=1 よりも i = i+1の方が微妙に早い、というお話に詳しくまとまっているので、ここでは箱ひげ図で可視化してみる。

方法

"i += 1"と" i = i + 1"をそれぞれ10,000,000回計算してそれを1セットとして、100回分計測して箱ひげ図で比較します。
箱ひげ図は、プログラマーのための統計学】箱ひげ図を参考にしました。

処理速度の比較
import time
import matplotlib.pyplot as plt

number_of_set = 100
list_1 = []# "i = i + 1"
list_2 = []# "i += 1"
n = int(1e+7)

# "i = i + 1"と"i += 1"の計測
for _ in range(number_of_set):
    # "i = i + 1"
    i = 0
    start_1 = time.time()
    for _ in range(n):
        i = i + 1
    list_1.append(time.time() - start_1)

    # "i += 1"
    i = 0
    start_2 = time.time()
    for _ in range(n):
        i += 1
    list_2.append(time.time() - start_2)

# 箱ひげ図
time = (list_1, list_2)# タプル化
fig, ax = plt.subplots()
bp = ax.boxplot(time)
ax.set_xticklabels(['i = i + 1', 'i += i'])
plt.title('100 times with 10,000,000 loops as one set')
plt.xlabel('type')
plt.ylabel('time [sec]')
plt.grid()
# 描画
plt.show()

スクリーンショット 2021-06-07 15.27.19.png

結論

箱ひげ図から定性的になりますが、"i = i + 1"の方が速い結果となりました。
ただ、"i += 1"の方がすっきりしているので、臨機応変に使い分けたいところです。

参考資料

[小ネタ] Pythonでは、 i+=1 よりも i = i+1の方が微妙に早い、というお話

2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1