cpuusage.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <rtthread.h>
  2. #include <rthw.h>
  3. #include <rtgui/event.h>
  4. #include <rtgui/rtgui_server.h>
  5. #include <rtgui/rtgui_system.h>
  6. #include "cpuusage.h"
  7. #define CPU_USAGE_CALC_TICK 10
  8. #define CPU_USAGE_LOOP 100
  9. static rt_uint8_t cpu_usage_major = 0, cpu_usage_minor= 0;
  10. static rt_uint32_t total_count = 0;
  11. static void cpu_usage_idle_hook()
  12. {
  13. rt_tick_t tick;
  14. rt_uint32_t count;
  15. volatile rt_uint32_t loop;
  16. if (total_count == 0)
  17. {
  18. loop = 0;
  19. /* get total count */
  20. rt_enter_critical();
  21. tick = rt_tick_get();
  22. while(rt_tick_get() - tick < CPU_USAGE_CALC_TICK)
  23. {
  24. total_count ++;
  25. while (loop < CPU_USAGE_LOOP) loop ++;
  26. }
  27. rt_exit_critical();
  28. }
  29. count = 0;
  30. loop = 0;
  31. /* get CPU usage */
  32. tick = rt_tick_get();
  33. while (rt_tick_get() - tick < CPU_USAGE_CALC_TICK)
  34. {
  35. count ++;
  36. while (loop < CPU_USAGE_LOOP) loop ++;
  37. }
  38. /* calculate major and minor */
  39. if (count < total_count)
  40. {
  41. count = total_count - count;
  42. cpu_usage_major = (count * 100) / total_count;
  43. cpu_usage_minor = ((count * 100) % total_count) * 100 / total_count;
  44. }
  45. else
  46. {
  47. total_count = count;
  48. /* no CPU usage */
  49. cpu_usage_major = 0;
  50. cpu_usage_minor = 0;
  51. }
  52. }
  53. void cpu_usage_get(rt_uint8_t *major, rt_uint8_t *minor)
  54. {
  55. RT_ASSERT(major != RT_NULL);
  56. RT_ASSERT(minor != RT_NULL);
  57. *major = cpu_usage_major;
  58. *minor = cpu_usage_minor;
  59. }
  60. void cpu_usage_init()
  61. {
  62. /* set idle thread hook */
  63. rt_thread_idle_sethook(cpu_usage_idle_hook);
  64. }
  65. extern rt_thread_t info_tid;
  66. static void cpu_thread_entry(void *parameter)
  67. {
  68. struct rtgui_event_command ecmd;
  69. RTGUI_EVENT_COMMAND_INIT(&ecmd);
  70. ecmd.type = RTGUI_CMD_USER_INT;
  71. ecmd.command_id = CPU_UPDATE;
  72. while (1)
  73. {
  74. rtgui_thread_send(info_tid, &ecmd.parent, sizeof(ecmd));
  75. rt_thread_delay(20);
  76. }
  77. }
  78. static rt_thread_t cpu_thread;
  79. void rt_hw_cpu_init(void)
  80. {
  81. cpu_usage_init();
  82. cpu_thread = rt_thread_create("cpu", cpu_thread_entry, RT_NULL, 384, 27, 5);
  83. if(cpu_thread != RT_NULL)
  84. rt_thread_startup(cpu_thread);
  85. }