Scheduler_example24_CPU_LOAD.ino 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. This sketch collects scheduling overhead and CPU Idle Sleep information.
  3. A task is invoked every 10 milliseconds for 10 seconds.
  4. CPU statistics are collected
  5. Compile and run once with _TASK_SLEEP_ON_IDLE_RUN enabled, then with _TASK_SLEEP_ON_IDLE_RUN disabled.
  6. Compare the results.
  7. */
  8. #define _TASK_ESP8266_DLY_THRESHOLD 50L
  9. #define _TASK_ESP32_DLY_THRESHOLD 40L
  10. #define _TASK_SLEEP_ON_IDLE_RUN
  11. #define _TASK_TIMECRITICAL
  12. #include <TaskScheduler.h>
  13. Scheduler ts;
  14. // Callback methods prototypes
  15. void Count();
  16. bool tOn(); void tOff();
  17. // Tasks
  18. Task c(10, TASK_FOREVER, &Count, &ts);
  19. Task t(10000, TASK_ONCE, NULL, &ts, true, &tOn, &tOff);
  20. volatile unsigned long c1, c2;
  21. bool tOn() {
  22. c1 = 0;
  23. c2 = 0;
  24. c.enable();
  25. return true;
  26. }
  27. void tOff() {
  28. c.disable();
  29. unsigned long cpuTot = ts.getCpuLoadTotal();
  30. unsigned long cpuCyc = ts.getCpuLoadCycle();
  31. unsigned long cpuIdl = ts.getCpuLoadIdle();
  32. Serial.print("Loop counts c1="); Serial.println(c1);
  33. Serial.print("Task counts c2="); Serial.println(c2);
  34. Serial.print("Total CPU time="); Serial.print(cpuTot); Serial.println(" micros");
  35. Serial.print("Scheduling Overhead CPU time="); Serial.print(cpuCyc); Serial.println(" micros");
  36. Serial.print("Idle Sleep CPU time="); Serial.print(cpuIdl); Serial.println(" micros");
  37. Serial.print("Productive work CPU time="); Serial.print(cpuTot - cpuIdl - cpuCyc); Serial.println(" micros");
  38. Serial.println();
  39. float idle = (float)cpuIdl / (float)cpuTot * 100;
  40. Serial.print("CPU Idle Sleep "); Serial.print(idle); Serial.println(" % of time.");
  41. float prod = (float)(cpuIdl + cpuCyc) / (float)cpuTot * 100;
  42. Serial.print("Productive work (not idle, not scheduling)"); Serial.print(100.00 - prod); Serial.println(" % of time.");
  43. }
  44. void setup() {
  45. // put your setup code here, to run once:
  46. Serial.begin(115200);
  47. delay(1000);
  48. Serial.println("CPU Time Measurement");
  49. Serial.println("Start");
  50. ts.startNow();
  51. t.delay();
  52. ts.cpuLoadReset();
  53. }
  54. void Count() {
  55. c2++; // number of task callback invocations
  56. // Try different delay intervals to see CPU statistics change
  57. // delay(1);
  58. // delay(5);
  59. // delay(10);
  60. // delay(20);
  61. }
  62. void loop() {
  63. // put your main code here, to run repeatedly:
  64. ts.execute();
  65. c1++; // number of loop() cycles
  66. }