LoginSignup
27
8

More than 5 years have passed since last update.

Python、最速のbool→int

Posted at

Pythonでbool型の値をint型に変換しようとしたとき、最速で処理できる書き方は何なのかと疑問に思った。
なので計測した。Python 3.6で検証。

検証用プログラム.py
import timeit

r = 3
n = 10 ** 7

def check(stmt):
    print('{}\t{}'.format(stmt, min(timeit.repeat(stmt, repeat=r, number=n))))

# False -> 0, True -> 1
check("x = False; int(x)")
check("x = True; int(x)")

check("x = False; (0, 1)[x]")
check("x = True; (0, 1)[x]")

check("x = False; [0, 1][x]")
check("x = True; [0, 1][x]")

check("x = False; { False: 0, True: 1 }[x]")
check("x = True; { False: 0, True: 1 }[x]")

check("x = False; 1 if x else 0")
check("x = True; 1 if x else 0")

check("x = False; x + 0")
check("x = True; x + 0")

check("x = False; x * 1")
check("x = True; x * 1")

check("x = False; x * x")
check("x = True; x * x")

check("x = False; x & 1")
check("x = True; x & 1")

check("x = False; x | 0")
check("x = True; x | 0")

check("x = False; x ^ 0")
check("x = True; x ^ 0")

# False -> 1, True -> 0
check("x = False; (1, 0)[x]")
check("x = True; (1, 0)[x]")

check("x = False; [1, 0][x]")
check("x = True; [1, 0][x]")

check("x = False; { False: 1, True: 0 }[x]")
check("x = True; { False: 1, True: 0 }[x]")

check("x = False; 0 if x else 1")
check("x = True; 0 if x else 1")

check("x = False; 1 - x")
check("x = True; 1 - x")

check("x = False; x ^ 1")
check("x = True; x ^ 1")

実験結果

検証に使ったPC。

  • パソコンA : Windows 10
  • パソコンB : CentOS 7

パソコンA

コード False→0 True→1
int(x) 1.899 1.902
(0, 1)[x] 0.548 0.536
[0, 1][x] 0.998 0.874
{ False: 0, True: 1 }[x] 1.868 1.929
1 if x else 0 0.367 0.378
x + 0 0.521 0.537
x * 1 0.530 0.544
x * x 0.519 0.534
x & 1 0.761 0.776
x | 0 0.825 0.890
x ^ 0 0.854 0.908
コード False→1 True→0
(1, 0)[x] 0.550 0.525
[1, 0][x] 1.005 0.989
{ False: 1, True: 0 }[x] 2.085 2.077
0 if x else 1 0.377 0.389
1 - x 0.559 0.574
x ^ 1 1.112 1.085

パソコンB

コード False→0 True→1
int(x) 0.980 0.989
(0, 1)[x] 0.213 0.216
[0, 1][x] 0.481 0.485
{ False: 0, True: 1 }[x] 0.825 0.826
1 if x else 0 0.151 0.159
x + 0 0.204 0.204
x * 1 0.203 0.209
x * x 0.202 0.206
x & 1 0.330 0.343
x | 0 0.336 0.356
x ^ 0 0.334 0.358
コード False→1 True→0
(1, 0)[x] 0.213 0.216
[1, 0][x] 0.480 0.487
{ False: 1, True: 0 }[x] 0.825 0.826
0 if x else 1 0.151 0.160
1 - x 0.205 0.198
x ^ 1 0.368 0.350

結論

条件演算子1 if x else 0を使う方法が一番速かった。
手軽さも考慮するとx + 0あたりも良さげ。int(x)が最も遅いのはちょっと意外。
変換処理部分を何回も使いまわすような場合や、別の計算機環境ではまた結果が異なるかもしれない。

あとQiitaに対する要望として、表中のコードのインライン表示の内部で縦棒(|)を使えるようにしてほしい。

27
8
0

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
27
8