Monday, April 12, 2021

Python3 find string

 


from datetime import datetime


def f1(s,r):
t1 = datetime.utcnow()
if r in s:
t2 = datetime.utcnow()
delta = t2 - t1
print(f'found in {delta.total_seconds()}')
else:
t2 = datetime.utcnow()
delta = t2 - t1
print(f'Not found in {delta.total_seconds()}')


def f2(s,r):
t1 = datetime.utcnow()
idx = s.find(r)
t2 = datetime.utcnow()
delta = t2 - t1
if idx > 0:
print(f'found in {delta.total_seconds()}')
else:
print(f'Not found in {delta.total_seconds()}')


if '__main__' == __name__:
s1 = '1'*10000
s2 = 'abc def ghi jkl mno pqr stu vwx yz'
s3 = '3'*10000
s = f'{s1} {s2} {s3}'
f1(s, 'ghi jkl')
f2(s, 'ghi jkl')


Kết quả cho thấy hàm str.find() tìm kiếm nhanh hơn.


No comments: