Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Testing how much a modulus operation can delay time based
- * operation of Arduino.
- *
- * Modulus is slow, so including it in calculations using
- * millis() prior to setting your prevMillis = millis() for
- * incremental time keeping can slow things down
- *
- * // The wrong way
- * something = (millis() - prevMillis) % something_else;
- * // long operation happend before we set prevMillis... DELAY
- * prevMillis = millis();
- * // The right way
- * increment = millis() - prevMillis;
- * prevMillis = millis();
- * // long operation happens after we have set prevMillis
- * something = increment % something_else;
- *
- * The times I get in my code are:
- * with % operation: 1332ms
- * sans % operation: 165ms
- */
- unsigned long int millisSinceStart = 0;
- unsigned long int prevMillis = 0;
- void setup() {
- Serial.begin(9600);
- }
- void loop() {
- unsigned long int start = millis();
- unsigned long int finish;
- // Caculate how many milliseconds since Arduino was reset
- // rolling over every 24 hours (used in clock program)
- for (int i = 0 ; i < 32000 ; i++ ) {
- millisSinceStart =
- (millisSinceStart + millis() - prevMillis) % 86400000;
- prevMillis = millis();
- }
- finish = millis();
- Serial.print("Calculation with % operation: ");
- Serial.println(finish - start);
- // Same without modulus operation (no rollover - will last
- // for 49.5 days then rollover to 0.
- start = millis();
- for (int i = 0 ; i < 32000 ; i++ ) {
- millisSinceStart =
- (millisSinceStart + millis() - prevMillis);
- prevMillis = millis();
- }
- finish = millis();
- Serial.print("Calculation sans % operation: ");
- Serial.println(finish - start);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement