首先說明,micropython跟python是沒有任何可比性的,python作為一種通用的語言,在擴展性上不是micropython能比的,比如大量的庫,可以方便的用C語言加模塊提升速度,有pypy這樣的帶JIT的解釋器,micropython是適合於單片機的系統雖然可以用C寫lib,但是需要重新編譯整個固件,此外,micropython也缺乏加載本地代碼的功能,比如加載C便宜的so庫。所以不要試圖用micropython代替python,這不是一個好主意,除非micropython支持的庫滿足你的使用了。
這篇文章主要是簡單的對比這兩個不同的實現的性能有何差別。
測試代碼有兩個,一個是一個大循環,一個是遞歸計算斐波那契數列,例子比較簡單,代碼如下:
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
可以看到,pypy速都還是很明顯的,喜聞樂見的是,pypy3甚至超過了pypy。
下邊在搞一下優化,micropython有@micropython.native,@micropython.viper兩個可以提速的裝飾器,通過翻譯成機器碼來提速,結果如下:
@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
其中fib部分由於返回值類型不固定viper失敗,所以改成了如下方式:
@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)
對性能有一定的影響,同代碼的native模式為52秒,直接解釋執行是87秒
也就是說,viper性能在循環方面,4倍於native 10倍於直接解釋。遞歸方面,viper速度是native的2倍是直接執行的3倍
當然,跟pypy的1.2秒,7.8秒還是慢3倍以上。
結論:
1.micropython解釋器的速度跟cpython差不多,都低於pypy
2.通過native或者viper兩個裝飾器,可以加速代碼,能到pypy一個數量級(慢3倍)
其實個人覺得python也可以考慮加上類似的技術來加速代碼,畢竟沒多少代碼量。