From 7a2beda2a976777a12829d31917e5404832d05bf Mon Sep 17 00:00:00 2001 From: Neil McKechnie Date: Mon, 8 Mar 2021 15:32:40 +0000 Subject: [PATCH] Add optional loop time monitor. By defining ENABLE_LOOP_MEASUREMENT as true in config.h, the loop measurement will be enabled. This measures the time between successive executions of the main CS loop to help identify if something is taking too long and holding up the other loop functions. --- CommandStation-EX.ino | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/CommandStation-EX.ino b/CommandStation-EX.ino index 2357638..1fe625a 100644 --- a/CommandStation-EX.ino +++ b/CommandStation-EX.ino @@ -134,4 +134,31 @@ void loop() LCD(2,F("Free RAM=%5db"), ramLowWatermark); } #endif + +// Optionally report average and maximum loop time +#if ENABLE_LOOP_MEASUREMENT + static unsigned long startTime = micros(); + static unsigned int maxElapsed = 0; + static unsigned long totalElapsed = 0; + static unsigned long count = 0; + static unsigned long lastOutput = millis(); + + unsigned long endTime = micros(); + unsigned int elapsed = endTime - startTime; + + if (elapsed > maxElapsed) maxElapsed = elapsed; + count++; + totalElapsed += elapsed; + + unsigned long currentMillis = millis(); + if (currentMillis - lastOutput >= 5000) { + DIAG(F("\nLoop: max=%dus ave=%dus\n"), maxElapsed, totalElapsed/count); + maxElapsed = 0; + totalElapsed = 0; + count = 0; + lastOutput = currentMillis; + } + startTime = micros(); +#endif + }