编程语言
首页 > 编程语言> > micropython格式化处理文本最快的方式(优化文本)

micropython格式化处理文本最快的方式(优化文本)

作者:互联网

在单片机中, 计算能力资源非常有限, 如何设计出更高执行效率的代码时嵌入式开发者的必修课程, 我通过统计和对比计算出了在micropython中最快的文本处理方法.

实验流程:

分别使用 string.join () , 文本加文本 , % 占位符 , string.format() 这四种方式 (micropython不支持f-string)来生成一段时间文本, 每一种方法执行五次, 每一次生成500次, 计算每种方法花费的时间.

实验脚本:

import time()

print ('method 1: (join)')
for i in range (1,6):
    t = time.ticks_ms ()
    for _ in range (5000):
        y,m,d,_,h,mi,s,_ = rtc.datetime ()
        v = ''.join((str(y),'-',str(m),'-',str(d),' ', str(h),':',str(mi),':',str(s)))
    print (i,' : ',"mt1 took ", round ((time.ticks_ms () - t)/1000,2), 's')

print ('method 2: (+)')
for i in range (1,6):
    t = time.ticks_ms ()
    for _ in range (5000):
        y,m,d,_,h,mi,s,_ = rtc.datetime ()
        # met1: ''.join((str(y),'-',str(m),'-',str(d),' ', str(h),':',str(m),':',str(s)))
        v = (str(y)+'-'+str(m)+'-'+str(d)+' '+ str(h)+':'+str(mi)+':'+str(s))# v = ''.join((str(y),'-',str(m),'-',str(d),' ', str(h),':',str(m),':',str(s)))
    print (i,' : ',"mt2 took ", round ((time.ticks_ms () - t)/1000,2), 's')

print ('method 3: (format % )')
for i in range (1,6):
    t = time.ticks_ms ()
    for _ in range (5000):
        y,m,d,_,h,mi,s,_ = rtc.datetime ()
        # met1: ''.join((str(y),'-',str(m),'-',str(d),' ', str(h),':',str(m),':',str(s)))
        v = "%d-%d-%d %d:%d:%d"%(y,m,d,h,mi,s)
    print (i,' : ',"mt3 took ", round ((time.ticks_ms () - t)/1000,2), 's')


print ('method 4: ( ''.format )')
for i in range (1,6):
    t = time.ticks_ms ()
    for _ in range (5000):
        y,m,d,_,h,mi,s,_ = rtc.datetime ()
        # met1: ''.join((str(y),'-',str(m),'-',str(d),' ', str(h),':',str(m),':',str(s)))
        v = '{0}-{1}-{2} {3}:{4}:{5}'.format (y,m,d,h,mi,s)
    print (i,' : ',"mt3 took ", round ((time.ticks_ms () - t)/1000,2), 's')

实验结果:

全部内容请查看原文
全部内容请查看原文
全部内容请查看原文

标签:micropython,格式化,ticks,mi,range,str,time,print,文本
来源: https://blog.csdn.net/qq_31269061/article/details/117903566