ElapsedTimer.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/Time.h>
  8. #include <LibCore/ElapsedTimer.h>
  9. #include <sys/time.h>
  10. #include <time.h>
  11. namespace Core {
  12. ElapsedTimer ElapsedTimer::start_new()
  13. {
  14. ElapsedTimer timer;
  15. timer.start();
  16. return timer;
  17. }
  18. void ElapsedTimer::start()
  19. {
  20. m_valid = true;
  21. timespec now_spec;
  22. clock_gettime(m_precise ? CLOCK_MONOTONIC : CLOCK_MONOTONIC_COARSE, &now_spec);
  23. m_origin_time.tv_sec = now_spec.tv_sec;
  24. m_origin_time.tv_usec = now_spec.tv_nsec / 1000;
  25. }
  26. void ElapsedTimer::reset()
  27. {
  28. m_valid = false;
  29. m_origin_time = { 0, 0 };
  30. }
  31. int ElapsedTimer::elapsed() const
  32. {
  33. VERIFY(is_valid());
  34. struct timeval now;
  35. timespec now_spec;
  36. clock_gettime(m_precise ? CLOCK_MONOTONIC : CLOCK_MONOTONIC_COARSE, &now_spec);
  37. now.tv_sec = now_spec.tv_sec;
  38. now.tv_usec = now_spec.tv_nsec / 1000;
  39. struct timeval diff;
  40. timeval_sub(now, m_origin_time, diff);
  41. return diff.tv_sec * 1000 + diff.tv_usec / 1000;
  42. }
  43. Time ElapsedTimer::elapsed_time() const
  44. {
  45. return Time::from_milliseconds(elapsed());
  46. }
  47. }