LoginSignup
0
2

More than 1 year has passed since last update.

【Python】for文の"_"(アンダースコア)の処理速度

Last updated at Posted at 2021-06-05

概要

普通のfor文と"_"を使ったfor文の処理速度を比較します。

処理速度の比較

それぞれ10億回ループ処理をします。

処理速度の比較
import time

n = int(1e+9)
normal = 0
under_score = 0

# 普通のfor文
start_normal = time.time()
for i in range(n):
    normal += 1
print('normal:{:.5f} sec'.format(time.time() - start_normal))

# "_"を使ったfor文
start_under_score = time.time()
for _ in range(n):
    under_score += 1
print('under_score:{:.5f} sec'.format(time.time() - start_under_score))
出力結果
normal:79.93061 sec
under_score:79.05743 sec

結論

"_"を使った方が約1%速い結果になりました。いや待てよ?1回だけでなんか胡散臭い!と思われる方がいると思います。私もその1人です。

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

箱ひげ図による比較
import time
import matplotlib.pyplot as plt

number_of_set = 100
normal_list = []
under_score_list = []
n = int(1e+7)
# 普通のforと"_"の計測
for _ in range(number_of_set):
    # 普通のfor文
    normal = 0
    start_normal = time.time()
    for i in range(n):
        normal += 1
    normal_list.append(time.time() - start_normal)

    # "_"を使ったfor文
    under_score = 0
    start_under_score = time.time()
    for _ in range(n):
        under_score += 1
    under_score_list.append(time.time() - start_under_score)

# 箱ひげ図
time = (normal_list, under_score_list)# タプル化
fig, ax = plt.subplots()
bp = ax.boxplot(time)
ax.set_xticklabels(['normal', 'under score'])
plt.title('100 times with 10,000,000 loops as one set')
plt.xlabel('type')
plt.ylabel('time')
plt.grid()
# 描画
plt.show()

スクリーンショット 2021-06-07 12.01.28.png
"_"の方が平均値では、速い結果となりました。縦軸の単位は秒です。

おまけ

使っているところを見たことはないが、"_"は変数として機能しているようです。
@shiracamusさんコメントありがとうございます。アンダースコア1つは、変数の値を使わずに捨てることを明示するための暗黙のルールになってるとのことです。以下のコードは変数として機能することの確認ですが、実際に使うのは避けましょう。
ちなみに変数名のルールは以下のようになっています。

・使用できる文字は a ~ z 、 A ~ Z 、 0 ~ 9 、アンダーバー(_)、漢字など
・一文字目に数値(0~9)は使用できない
・一文字目にアンダーバーは使用できるが特別な用途で使用されているケースが多いので通常は使用しない方がいい
・大文字と小文字は区別される
・予約語は使用できない
(引用:https://www.javadrive.jp/python/var/index1.html#section1)

# 普通のfor文
print('---普通のfor文---')
for i in range(3):
    print('値:{}, 型:{}'.format(i, type(i)))

# "_"を使ったfor文
print('---"_"を使ったfor文---')
for _ in range(3):
    print('値:{}, 型:{}'.format(_, type(_)))
出力結果
---普通のfor文---
値:0, 型:<class 'int'>
値:1, 型:<class 'int'>
値:2, 型:<class 'int'>
---"_"を使ったfor文---
値:0, 型:<class 'int'>
値:1, 型:<class 'int'>
値:2, 型:<class 'int'>

編集履歴

(2021/06/07) 内容:箱ひげ図の追加、まとめの"_"のルールについて修正

0
2
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
0
2