random.getrandbits(1)要快得多。如果您真的想要布尔值而不是long值,那么
bool(random.getrandbits(1))
仍然是两倍的速度
random.choice([True, False])
两种解决方案都需要
import random
如果最大的速度不是优先考虑的话,那么
random.choice阅读肯定会更好
$ python -m timeit -s "import random" "random.choice([True, False])"1000000 loops, best of 3: 0.904 usec per loop$ python -m timeit -s "import random" "random.choice((True, False))" 1000000 loops, best of 3: 0.846 usec per loop$ python -m timeit -s "import random" "random.getrandbits(1)"1000000 loops, best of 3: 0.286 usec per loop$ python -m timeit -s "import random" "bool(random.getrandbits(1))"1000000 loops, best of 3: 0.441 usec per loop$ python -m timeit -s "import random" "not random.getrandbits(1)"1000000 loops, best of 3: 0.308 usec per loop$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"1000000 loops, best of 3: 0.262 usec per loop # not takes about 20us of this
在看到@Pavel的答案后添加了此内容
$ python -m timeit -s "from random import random" "random() < 0.5"10000000 loops, best of 3: 0.115 usec per loop
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)