在python中,除法与移位

问题描述 投票:0回答:1

在python中,有除法(//,/)和shift(>>,<

使用移位而不是除法运算符有什么好处吗?!

python division shift
1个回答
1
投票

使用以下代码进行测量之后,移位似乎稍慢一些,但并不明显,并且在我的计算机上,您的结果可能会有所不同。

我得到以下答案:

It took 42.1938125s for division by 2
It took 43.217766499999996s for integer division by 2
It took 47.926054599999986s for shift by 1
It took 41.82601500000001s for division by 4
It took 43.20513730000002s for integer division by 4
It took 48.33005560000004s for shift by 2
import timeit
import random

random.seed(42)
DATA = [random.randint(0,10000) for _ in range(400)]

def measure(func, name):
    time = timeit.timeit(lambda: [func(val) for val in DATA], number=1000000)
    print(f"It took {time}s for {name}")

measure(lambda x:x / 2, "division by 2")
measure(lambda x:x // 2, "integer division by 2")
measure(lambda x:x >> 1, "shift by 1")
measure(lambda x:x / 4, "division by 4")
measure(lambda x:x // 4, "integer division by 4")
measure(lambda x:x >> 2, "shift by 2")
© www.soinside.com 2019 - 2024. All rights reserved.