Advertisement
markruff

Arduino circular counter modulus vs branch

Jan 19th, 2016
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. /*
  2.  * When counting in a circular fashion 0, 1, 2, 3, 0, 1 ...
  3.  * branching is more efficient than modulus (%) operation
  4.  *
  5.  *
  6.  *
  7.  */
  8.  
  9. int counter = 0;
  10.  
  11. void setup() {
  12.   Serial.begin(9600);
  13. }
  14.  
  15. void loop() {
  16.   unsigned long int start;
  17.   unsigned long int finish;
  18.  
  19.   // modulus operation
  20.  
  21.   counter = 0;
  22.   start = millis();
  23.   for ( int i = 0 ; i < 32000 ; i++ ) {
  24.     counter = (counter + 1) % 4;
  25.   }
  26.   finish = millis();
  27.   Serial.print("modulus time: ");
  28.   Serial.println(finish - start);
  29.  
  30.   // branch operation
  31.  
  32.   counter = 0;
  33.   start = millis();  
  34.   for ( int i = 0 ; i < 32000 ; i++ ) {
  35.     counter = counter + 1;
  36.     if (counter == 4) {
  37.       counter = 0;
  38.     }
  39.   }
  40.   finish = millis();
  41.   Serial.print("branch time: ");
  42.   Serial.println(finish - start);
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement