cpuusage.c 1.4 KB

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