chrono_utils_test.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (C) 2017 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "android-base/chrono_utils.h"
  17. #include <time.h>
  18. #include <chrono>
  19. #include <sstream>
  20. #include <string>
  21. #include <thread>
  22. #include <gtest/gtest.h>
  23. namespace android {
  24. namespace base {
  25. std::chrono::seconds GetBootTimeSeconds() {
  26. struct timespec now;
  27. clock_gettime(CLOCK_BOOTTIME, &now);
  28. auto now_tp = boot_clock::time_point(std::chrono::seconds(now.tv_sec) +
  29. std::chrono::nanoseconds(now.tv_nsec));
  30. return std::chrono::duration_cast<std::chrono::seconds>(now_tp.time_since_epoch());
  31. }
  32. // Tests (at least) the seconds accuracy of the boot_clock::now() method.
  33. TEST(ChronoUtilsTest, BootClockNowSeconds) {
  34. auto now = GetBootTimeSeconds();
  35. auto boot_seconds =
  36. std::chrono::duration_cast<std::chrono::seconds>(boot_clock::now().time_since_epoch());
  37. EXPECT_EQ(now, boot_seconds);
  38. }
  39. template <typename T>
  40. void ExpectAboutEqual(T expected, T actual) {
  41. auto expected_upper_bound = expected * 1.05f;
  42. auto expected_lower_bound = expected * .95;
  43. EXPECT_GT(expected_upper_bound, actual);
  44. EXPECT_LT(expected_lower_bound, actual);
  45. }
  46. TEST(ChronoUtilsTest, TimerDurationIsSane) {
  47. auto start = boot_clock::now();
  48. Timer t;
  49. std::this_thread::sleep_for(50ms);
  50. auto stop = boot_clock::now();
  51. auto stop_timer = t.duration();
  52. auto expected = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
  53. ExpectAboutEqual(expected, stop_timer);
  54. }
  55. TEST(ChronoUtilsTest, TimerOstream) {
  56. Timer t;
  57. std::this_thread::sleep_for(50ms);
  58. auto stop_timer = t.duration().count();
  59. std::stringstream os;
  60. os << t;
  61. decltype(stop_timer) stop_timer_from_stream;
  62. os >> stop_timer_from_stream;
  63. EXPECT_NE(0, stop_timer);
  64. ExpectAboutEqual(stop_timer, stop_timer_from_stream);
  65. }
  66. } // namespace base
  67. } // namespace android