blob: da442f455ba9d339a344c8287b5fea4baff35763 [file] [log] [blame]
James Hawkinse78ea772017-03-24 11:43:02 -07001/*
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>
Tom Cherryede0d532017-07-06 14:20:11 -070022#include <sstream>
23#include <string>
24#include <thread>
James Hawkinse78ea772017-03-24 11:43:02 -070025
26#include <gtest/gtest.h>
27
28namespace android {
29namespace base {
30
31std::chrono::seconds GetBootTimeSeconds() {
32 struct timespec now;
Josh Gao0b35b182017-05-01 21:56:28 +000033 clock_gettime(CLOCK_BOOTTIME, &now);
James Hawkinse78ea772017-03-24 11:43:02 -070034
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.
41TEST(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
Tom Cherryede0d532017-07-06 14:20:11 -070048template <typename T>
49void 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
56TEST(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
67TEST(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
James Hawkinse78ea772017-03-24 11:43:02 -070079} // namespace base
Tom Cherryede0d532017-07-06 14:20:11 -070080} // namespace android