ElapsedTimer.cpp 908 B

12345678910111213141516171819202122232425262728293031323334353637
  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. void ElapsedTimer::start()
  13. {
  14. m_valid = true;
  15. timespec now_spec;
  16. clock_gettime(m_precise ? CLOCK_MONOTONIC : CLOCK_MONOTONIC_COARSE, &now_spec);
  17. m_origin_time.tv_sec = now_spec.tv_sec;
  18. m_origin_time.tv_usec = now_spec.tv_nsec / 1000;
  19. }
  20. int ElapsedTimer::elapsed() const
  21. {
  22. VERIFY(is_valid());
  23. struct timeval now;
  24. timespec now_spec;
  25. clock_gettime(m_precise ? CLOCK_MONOTONIC : CLOCK_MONOTONIC_COARSE, &now_spec);
  26. now.tv_sec = now_spec.tv_sec;
  27. now.tv_usec = now_spec.tv_nsec / 1000;
  28. struct timeval diff;
  29. timeval_sub(now, m_origin_time, diff);
  30. return diff.tv_sec * 1000 + diff.tv_usec / 1000;
  31. }
  32. }