main.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <AK/CircularQueue.h>
  2. #include <LibCore/CProcessStatisticsReader.h>
  3. #include <LibGUI/GApplication.h>
  4. #include <LibGUI/GPainter.h>
  5. #include <LibGUI/GWidget.h>
  6. #include <LibGUI/GWindow.h>
  7. class GraphWidget final : public GWidget {
  8. C_OBJECT(GraphWidget)
  9. public:
  10. GraphWidget()
  11. : GWidget(nullptr)
  12. {
  13. start_timer(1000);
  14. }
  15. virtual ~GraphWidget() override {}
  16. private:
  17. virtual void timer_event(CTimerEvent&) override
  18. {
  19. unsigned busy;
  20. unsigned idle;
  21. get_cpu_usage(busy, idle);
  22. unsigned busy_diff = busy - m_last_busy;
  23. unsigned idle_diff = idle - m_last_idle;
  24. m_last_busy = busy;
  25. m_last_idle = idle;
  26. float cpu = (float)busy_diff / (float)(busy_diff + idle_diff);
  27. m_cpu_history.enqueue(cpu);
  28. update();
  29. }
  30. virtual void paint_event(GPaintEvent& event) override
  31. {
  32. GPainter painter(*this);
  33. painter.add_clip_rect(event.rect());
  34. painter.fill_rect(event.rect(), Color::Black);
  35. int i = m_cpu_history.capacity() - m_cpu_history.size();
  36. for (auto cpu_usage : m_cpu_history) {
  37. painter.draw_line(
  38. { i, rect().bottom() },
  39. { i, (int)(height() - (cpu_usage * (float)height())) },
  40. Color::from_rgb(0xaa6d4b));
  41. ++i;
  42. }
  43. }
  44. static void get_cpu_usage(unsigned& busy, unsigned& idle)
  45. {
  46. busy = 0;
  47. idle = 0;
  48. auto all_processes = CProcessStatisticsReader::get_all();
  49. for (auto& it : all_processes) {
  50. for (auto& jt : it.value.threads) {
  51. if (it.value.pid == 0)
  52. idle += jt.times_scheduled;
  53. else
  54. busy += jt.times_scheduled;
  55. }
  56. }
  57. }
  58. CircularQueue<float, 30> m_cpu_history;
  59. unsigned m_last_busy { 0 };
  60. unsigned m_last_idle { 0 };
  61. };
  62. int main(int argc, char** argv)
  63. {
  64. GApplication app(argc, argv);
  65. auto window = GWindow::construct();
  66. window->set_window_type(GWindowType::MenuApplet);
  67. window->resize(30, 16);
  68. auto widget = GraphWidget::construct();
  69. window->set_main_widget(widget);
  70. window->show();
  71. return app.exec();
  72. }