James Hawkins | 9957497 | 2017-03-24 11:43:02 -0700 | [diff] [blame] | 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 | |
Josh Gao | 09b8d4f | 2017-04-28 12:39:48 -0700 | [diff] [blame^] | 19 | #include <err.h> |
James Hawkins | 9957497 | 2017-03-24 11:43:02 -0700 | [diff] [blame] | 20 | #include <time.h> |
| 21 | |
| 22 | #include <chrono> |
| 23 | |
| 24 | #include <gtest/gtest.h> |
| 25 | |
| 26 | namespace android { |
| 27 | namespace base { |
| 28 | |
Josh Gao | 09b8d4f | 2017-04-28 12:39:48 -0700 | [diff] [blame^] | 29 | #if defined(__linux__) |
James Hawkins | 9957497 | 2017-03-24 11:43:02 -0700 | [diff] [blame] | 30 | std::chrono::seconds GetBootTimeSeconds() { |
| 31 | struct timespec now; |
Josh Gao | 09b8d4f | 2017-04-28 12:39:48 -0700 | [diff] [blame^] | 32 | if (clock_gettime(CLOCK_BOOTTIME, &now) != 0) { |
| 33 | err(1, "clock_gettime failed"); |
| 34 | } |
James Hawkins | 9957497 | 2017-03-24 11:43:02 -0700 | [diff] [blame] | 35 | |
| 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. |
| 42 | TEST(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 Gao | 09b8d4f | 2017-04-28 12:39:48 -0700 | [diff] [blame^] | 48 | #endif // defined(__linux__) |
James Hawkins | 9957497 | 2017-03-24 11:43:02 -0700 | [diff] [blame] | 49 | |
| 50 | } // namespace base |
Josh Gao | 09b8d4f | 2017-04-28 12:39:48 -0700 | [diff] [blame^] | 51 | } // namespace android |