cpuusage.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <rtthread.h>
  2. #include <rthw.h>
  3. #include "board.h"
  4. static rt_uint8_t cpu_usage_major = 0, cpu_usage_minor= 0;
  5. static rt_uint32_t idle_begin = 0,idle_count = 0;
  6. static rt_uint32_t run_begin = 0,run_count = 0;
  7. static rt_uint32_t update_tick = 0;
  8. static wtdog_count = 0;
  9. #define jiffies 0
  10. void cpu_usage_idle_hook()
  11. {
  12. wtdog_count = 0;
  13. }
  14. void thread_switch_hook(struct rt_thread *from, struct rt_thread *to)
  15. {
  16. //leave idle
  17. if (from->init_priority == RT_THREAD_PRIORITY_MAX - 1)
  18. {
  19. run_begin = jiffies;
  20. idle_count += jiffies-idle_begin;
  21. }
  22. //enter idle
  23. if (to->init_priority == RT_THREAD_PRIORITY_MAX - 1)
  24. {
  25. idle_begin = jiffies;
  26. run_count += jiffies-run_begin;
  27. }
  28. //enter main once 500ms
  29. else if (to->init_priority == 2)
  30. {
  31. register rt_uint32_t total_count;
  32. run_count += jiffies-run_begin;
  33. run_begin = jiffies;
  34. total_count = run_count+idle_count;
  35. cpu_usage_major = (run_count * 100) / total_count;
  36. cpu_usage_minor = ((run_count * 100) % total_count) * 100 / total_count;
  37. idle_count = run_count = 0;
  38. update_tick = rt_tick_get();
  39. }
  40. }
  41. #if defined(RT_USING_FINSH)
  42. #include <finsh.h>
  43. void cpu_usage()
  44. {
  45. //long time no update?? 100%
  46. if ((rt_tick_get() - update_tick) > 1000)
  47. {
  48. cpu_usage_major = 100;
  49. cpu_usage_minor = 0;
  50. }
  51. rt_kprintf("Cpu Usage: %d.%d\n",cpu_usage_major,cpu_usage_minor);
  52. }
  53. void rt_usage_info(rt_uint32_t *major, rt_uint32_t *minor)
  54. {
  55. //long time no update?? 100%
  56. if ((rt_tick_get() - update_tick) > 1000)
  57. {
  58. cpu_usage_major = 100;
  59. cpu_usage_minor = 0;
  60. }
  61. if (major)
  62. *major = cpu_usage_major;
  63. if (minor)
  64. *minor = cpu_usage_minor;
  65. }
  66. RTM_EXPORT(rt_usage_info);
  67. FINSH_FUNCTION_EXPORT(cpu_usage, cpu usage);
  68. MSH_CMD_EXPORT(cpu_usage, cpu usage);
  69. #endif //RT_USING_FINSH