## MicroPython与Python速度对比

try:
import utime as time
except:
import time

def bigloop():
s=0
for i in range(1000000000):
s+=i

def fib(n):
if n==0:
return 0
if n==1:
return 1
return fib(n-1)+fib(n-2)

t=time.time()
bigloop()
print("bigloop time:",time.time()-t)
t=time.time()
print("The 40th fibric is:",fib(40))
print("fibn time:",time.time()-t)

[yafeng@ArchV ~]$python micromark.py bigloop time: 60.44254755973816 The 40th fibric is: 102334155 fibn time: 48.39746880531311  [yafeng@ArchV ~]$ micropython micromark.py
bigloop time: 51.92846608161926
The 40th fibric is: 102334155
fibn time: 65.70703196525574

可以看到，效率基本是一样的，循环micropython稍快一点，递归cpython稍快一点，顺便贴一下pypy pypy3的结果：
[yafeng@ArchV ~]$pypy micromark.py ('bigloop time:', 1.7053859233856201) ('The 40th fibric is:', 102334155) ('fibn time:', 7.795623064041138) [yafeng@ArchV ~]$ pypy3 micromark.py
bigloop time: 1.2033970355987549
The 40th fibric is: 102334155
fibn time: 7.820451974868774

@micropython.native

[yafeng@ArchV ~]$micropython micromark.py bigloop time: 23.538330078125 The 40th fibric is: 102334155 fibn time: 40.44101715087891 @micropython.viper [yafeng@ArchV ~]$ micropython micromark.py
bigloop time: 5.683197021484375
The 40th fibric is: 102334155
fibn time: 24.39595413208008

@micropython.viper
def num(x):
return x

@micropython.viper
def fib(n:int)->object:
if n==0:
return num(0)
if n==1:
return num(1)
return fib(n-1)+fib(n-2)

1.micropython解释器的速度跟cpython差不多，都低于pypy

2.通过native或者viper两个装饰器，可以加速代码，能到pypy一个数量级（慢3倍）

posted on 2018-05-14 08:33  yafeng  阅读(16033)  评论(1编辑  收藏  举报