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 17 #include "android-base/chrono_utils.h" 18 19 #include <time.h> 20 21 #include <chrono> 22 #include <sstream> 23 #include <string> 24 #include <thread> 25 26 #include <gtest/gtest.h> 27 28 namespace android { 29 namespace base { 30 31 std::chrono::seconds GetBootTimeSeconds() { 32 struct timespec now; 33 clock_gettime(CLOCK_BOOTTIME, &now); 34 35 auto now_tp = boot_clock::time_point(std::chrono::seconds(now.tv_sec) + 36 std::chrono::nanoseconds(now.tv_nsec)); 37 return std::chrono::duration_cast<std::chrono::seconds>(now_tp.time_since_epoch()); 38 } 39 40 // Tests (at least) the seconds accuracy of the boot_clock::now() method. 41 TEST(ChronoUtilsTest, BootClockNowSeconds) { 42 auto now = GetBootTimeSeconds(); 43 auto boot_seconds = 44 std::chrono::duration_cast<std::chrono::seconds>(boot_clock::now().time_since_epoch()); 45 EXPECT_EQ(now, boot_seconds); 46 } 47 48 template <typename T> 49 void ExpectAboutEqual(T expected, T actual) { 50 auto expected_upper_bound = expected * 1.05f; 51 auto expected_lower_bound = expected * .95; 52 EXPECT_GT(expected_upper_bound, actual); 53 EXPECT_LT(expected_lower_bound, actual); 54 } 55 56 TEST(ChronoUtilsTest, TimerDurationIsSane) { 57 auto start = boot_clock::now(); 58 Timer t; 59 std::this_thread::sleep_for(50ms); 60 auto stop = boot_clock::now(); 61 auto stop_timer = t.duration(); 62 63 auto expected = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); 64 ExpectAboutEqual(expected, stop_timer); 65 } 66 67 TEST(ChronoUtilsTest, TimerOstream) { 68 Timer t; 69 std::this_thread::sleep_for(50ms); 70 auto stop_timer = t.duration().count(); 71 std::stringstream os; 72 os << t; 73 decltype(stop_timer) stop_timer_from_stream; 74 os >> stop_timer_from_stream; 75 EXPECT_NE(0, stop_timer); 76 ExpectAboutEqual(stop_timer, stop_timer_from_stream); 77 } 78 79 } // namespace base 80 } // namespace android 81