Fall in love with the python series-python performance (ten): bisect speeds up the query of ordered lists

If the amount of data is large, the list will become very slow even using index. Let’s do an experiment and use the binary search module bisect

import  time
import bisect

index=1<<25#1<<25表示2^25
ls=[i for i  in  range(1<<28)]#1<<28表示2^28
start=time.time()
a1 = bisect.bisect(ls,index )
print('bisect spend time:',time.time()-start)
print(a1)
start=time.time()
a2 =ls.index(index)
print('index spend time:',time.time()-start)
print(a2)

operation result:

bisect spend time: 5.078315734863281e-05
33554433
index spend time: 0.2695434093475342
33554432

The result is too big, several orders of magnitude

Guess you like

Origin blog.csdn.net/zhou_438/article/details/109285272