程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Efficiency of Python numerical comparison

編輯:Python

Python Numerical comparison of operational efficiency :>,<,==,!=,>= and <=


python Numerical comparison operation has 6 Kind of , Respectively >,<,==,!=,>= and <=. How efficient they are ? Which method is the most efficient ? This article uses timeit To test the efficiency of the comparison operation .
The procedure is as follows :

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)

This is only if Statement , give the result as follows :

Comparison operations Time spent >3.2038074<2.7034741==2.6940471000000006!=3.285996800000001>=3.205210300000001<=2.6961838999999994

add else Statement rule :

Comparison operations Time spent >3.2270024<3.2400326==3.2511219999999996!=3.1877201999999993>=3.2120345000000015<=3.2339978999999985

In general , The first branch saves time . The second branch will take a little more time .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved