cpuusage.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. *
  8. */
  9. #include <rtthread.h>
  10. #include <rthw.h>
  11. #define CPU_USAGE_CALC_TICK 10
  12. #define CPU_USAGE_LOOP 100
  13. static rt_uint8_t cpu_usage_major = 0, cpu_usage_minor= 0;
  14. static rt_uint32_t total_count = 0;
  15. static void cpu_usage_idle_hook()
  16. {
  17. rt_tick_t tick;
  18. rt_uint32_t count;
  19. volatile rt_uint32_t loop;
  20. if (total_count == 0)
  21. {
  22. /* get total count */
  23. rt_enter_critical();
  24. tick = rt_tick_get();
  25. while(rt_tick_get() - tick < CPU_USAGE_CALC_TICK)
  26. {
  27. total_count ++;
  28. loop = 0;
  29. while (loop < CPU_USAGE_LOOP) loop ++;
  30. }
  31. rt_exit_critical();
  32. }
  33. count = 0;
  34. /* get CPU usage */
  35. tick = rt_tick_get();
  36. while (rt_tick_get() - tick < CPU_USAGE_CALC_TICK)
  37. {
  38. count ++;
  39. loop = 0;
  40. while (loop < CPU_USAGE_LOOP) loop ++;
  41. }
  42. /* calculate major and minor */
  43. if (count < total_count)
  44. {
  45. count = total_count - count;
  46. cpu_usage_major = (count * 100) / total_count;
  47. cpu_usage_minor = ((count * 100) % total_count) * 100 / total_count;
  48. }
  49. else
  50. {
  51. total_count = count;
  52. /* no CPU usage */
  53. cpu_usage_major = 0;
  54. cpu_usage_minor = 0;
  55. }
  56. }
  57. void cpu_usage_get(rt_uint8_t *major, rt_uint8_t *minor)
  58. {
  59. RT_ASSERT(major != RT_NULL);
  60. RT_ASSERT(minor != RT_NULL);
  61. *major = cpu_usage_major;
  62. *minor = cpu_usage_minor;
  63. }
  64. void cpu_usage_init()
  65. {
  66. /* set idle thread hook */
  67. rt_thread_idle_sethook(cpu_usage_idle_hook);
  68. }