0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python、int → boolへの変換速度

Last updated at Posted at 2019-06-18

int → boolへの変換速度

ココの記事に啓蒙されたのと
自分がint → boolの変換を多用する場面が出てきたので、以下のやり方のうちどれが速いかテストした。
(※コメントで0以外の場合もTrueになるという指摘があったため0!=aも追記)
bool(a)
a == 1
a & 0b1
a != 0

結論

(a==1)が最も速い

code time(μs)
bool(a) 3960
a == 1 1710
a & 0b1 2113
a != 0 1802

※すべて小数点以下切り捨て
※3回分の計測の平均値を算出

環境とコード

OS: Ubuntu 18.04 LTS(64bit)
CPU: Intel Corei5-8250U
メモリは速度わからなかったが8GBを1枚つんでいる
Python: Python 3.6.8

コードは以下の通り

import time

a = 1
b = False
start = time.time()
for i in range(10000):
   b = bool(a)
print("time1: " + str(time.time()-start))

b = False
start = time.time()
for i in range(10000):
   b = (a==1)
print("time2: " + str(time.time()-start))

b = False
start = time.time()
for i in range(10000):
   b = (a & 0b1)
print("time3: " + str(time.time()-start))

b = False
start = time.time()
for i in range(10000):
   b = (a!=0)
print("time4: " + str(time.time()-start)) 

総論

上のリンクも合わせて、intとboolの相互変換は自分で作ったほうが速い説ありますね
それと `a==1'と'a!=0'では前者のほうが微妙に速い(多分bit反転の時間差)ので0or1のみを扱う場合は前者を使いましょう。
もしかするとメソッドを呼ぶのに時間かかってるだけなのかな?

余談: 訂正前から大幅に数値上がったんですけど、バックグラウンドで変なの動いてるのかな...(汗

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?