如果我想在Python中修改二进制数,我有两种方法可以做到。
我认为经过仔细的实施,第一种方式总是比第二种方式更快......直到今天。
考虑以下Python代码,它们以两种方式执行类似的无意义工作并测量其运行时间:
import time
def test(i):
num = 2**i
print("2**{0}".format(i))
start = time.time()
for _ in range(10000):
mask = 1
copyNum = num
while copyNum:
copyNum &= ~mask
mask <<= 1
end = time.time()
print("bit:", end -start)
start = time.time()
for _ in range(10000):
bits = list(bin(num)[2:])
for i in range(len(bits)):
bits[i] = '0'
end = time.time()
print("list:", end - start)
if __name__ == "__main__":
for i in range(100):
test(i)
以下是输出的一些部分:
2**0
bit: 0.0030112266540527344
list: 0.009064674377441406
2**1
bit: 0.003314495086669922
list: 0.009698867797851562
...
2**6
bit: 0.010007143020629883
list: 0.010907173156738281
2**7
bit: 0.010860681533813477
list: 0.01178431510925293
...
2**50
bit: 0.08656668663024902
list: 0.03987693786621094
2**51
bit: 0.10903549194335938
list: 0.036728620529174805
...
2**98
bit: 0.20895171165466309
list: 0.0722191333770752
2**99
bit: 0.23352742195129395
list: 0.08042550086975098
结果清楚地表明,当二进制数足够大时,“列表操作”比“位操作”更快。
P.S。我在Python 3中做了这些测试