blob: 1f1ce15b1605b38f2e7f9254c7a43448f05d3ff8 [file] [log] [blame]
James Hawkins99574972017-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
Josh Gao09b8d4f2017-04-28 12:39:48 -070019#include <err.h>
James Hawkins99574972017-03-24 11:43:02 -070020#include <time.h>
21
22#include <chrono>
23
24#include <gtest/gtest.h>
25
26namespace android {
27namespace base {
28
Josh Gao09b8d4f2017-04-28 12:39:48 -070029#if defined(__linux__)
James Hawkins99574972017-03-24 11:43:02 -070030std::chrono::seconds GetBootTimeSeconds() {
31 struct timespec now;
Josh Gao09b8d4f2017-04-28 12:39:48 -070032 if (clock_gettime(CLOCK_BOOTTIME, &now) != 0) {
33 err(1, "clock_gettime failed");
34 }
James Hawkins99574972017-03-24 11:43:02 -070035
36 auto now_tp = boot_clock::time_point(std::chrono::seconds(now.tv_sec) +
37 std::chrono::nanoseconds(now.tv_nsec));
38 return std::chrono::duration_cast<std::chrono::seconds>(now_tp.time_since_epoch());
39}
40
41// Tests (at least) the seconds accuracy of the boot_clock::now() method.
42TEST(ChronoUtilsTest, BootClockNowSeconds) {
43 auto now = GetBootTimeSeconds();
44 auto boot_seconds =
45 std::chrono::duration_cast<std::chrono::seconds>(boot_clock::now().time_since_epoch());
46 EXPECT_EQ(now, boot_seconds);
47}
Josh Gao09b8d4f2017-04-28 12:39:48 -070048#endif // defined(__linux__)
James Hawkins99574972017-03-24 11:43:02 -070049
50} // namespace base
Josh Gao09b8d4f2017-04-28 12:39:48 -070051} // namespace android