天天看點

一條随手的Arduino sketch優化 以Examples-02.Digital-Debounce為例

原文的代碼 暫時去掉注釋,便于顯示重點。

編譯結果:

Sketch uses 1116 bytes (3%) of program storage space. Maximum is 30720 bytes.

Global variables use 19 bytes (0%) of dynamic memory, leaving 2029 bytes for local variables. Maximum is 2048 bytes.

優化手段1:選用夠用的資料類型,這裡面的int對象,都是小于255的,可以換成byte:

  

Sketch uses 1074 bytes (3%) of program storage space. Maximum is 30720 bytes.

Global variables use 17 bytes (0%) of dynamic memory, leaving 2031 bytes for local variables. Maximum is 2048 bytes.

效果:

程式空間減少42位元組;SRAM減少2位元組。

繼續淦:

裡面有一個函數在相近的位置,用了兩遍,且貌似挺複雜的,就是:millis();

将其合二為一,但是又要增加一個全局變量,試試效果:

  編譯結果:

Sketch uses 1052 bytes (3%) of program storage space. Maximum is 30720 bytes.

又幹掉22位元組的程式空間,SRAM竟然沒變?

(1166-1052)/1166 = 104/1166 = 9.8%

将近10%的優化成果,這還沒使用骨灰級的寄存器大法來優化pinMode和digitalRead/Write。

後續再試:const byte debounceDelay    = 50; 結果還是1052、17,看來是編譯器自動将其優化了。