Python 数值比较运算效率:>,<,==,!=,>=和<=
python数值比较运算有6种,分别为>,<,==,!=,>=和 <=。他们的运算效率如何?采用哪种方式最高效?本文通过使用timeit来测试比较运算的效率。
程序如下:
import timeit
def func1():
for i in range(100000):
if i > 0:
k = 2
def func2():
for i in range(100000):
if i < 0:
k = 2
def func3():
for i in range(100000):
if i == 0:
k = 2
def func4():
for i in range(100000):
if i != 0:
k = 2
def func5():
for i in range(100000):
if i >= 0:
k = 2
def func6():
for i in range(100000):
if i <= 0:
k = 2
if __name__ == '__main__':
func1()
func=[func1,func2,func3,func4,func5,func6]
op = [">","<","==","!=",">=","<="]
for j in range(6):
v = 0
timer = timeit.Timer(func[j])
v+= timer.timeit(number=1000)
print(op[j],":",v)
这是只有if语句的情况,结果如下:
比较运算 | 所用时间 |
---|
> | 3.2038074 | < | 2.7034741 | == | 2.6940471000000006 | != | 3.285996800000001 | >= | 3.205210300000001 | <= | 2.6961838999999994 |
加上else语句则:
比较运算 | 所用时间 |
---|
> | 3.2270024 | < | 3.2400326 | == | 3.2511219999999996 | != | 3.1877201999999993 | >= | 3.2120345000000015 | <= | 3.2339978999999985 |
一般情况下,第一个分支比较节省时间。第二个分支会耗时稍微多一些。
|