python中测试方法所用的时间—timeit

发布时间 2023-05-29 18:05:15作者: 阿苏勒的吕归尘

方法代码

使用timeit方法测试两个函数的运行速度

import timeit

strlist=['This is a long string that will nit keep in memory.' for n in range(10000)]

def use_join():#使用字符串的join方法连接多个字符串
return ''.join(strlist)
def ues_plus():#使用运算符+连接多个字符串
result =''
for strtemp in strlist:
result =result+strtemp
return result
startime1=timeit.default_timer()
print("The start time is :",startime1)
use_join()
print("The time difference is:",timeit.default_timer()-startime1)
startime2=timeit.default_timer()
print("The start time is:",startime2)
ues_plus()
print("The time difference is:",timeit.default_timer()-startime2)

运行结果

image