1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "time_common.h"
17 #include "time_hilog.h"
18
19
20 namespace OHOS {
21 namespace MiscServices {
22 namespace {
23 static const int MILLI_TO_SEC = 1000LL;
24 static const int NANO_TO_SEC = 1000000000LL;
25 constexpr int32_t NANO_TO_MILLI = NANO_TO_SEC / MILLI_TO_SEC;
26 }
27
GetWallTimeMs(int64_t & time)28 int32_t TimeUtils::GetWallTimeMs(int64_t &time)
29 {
30 struct timespec tv {};
31 if (!GetTimeByClockId(CLOCK_REALTIME, tv)) {
32 TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
33 return E_TIME_SA_DIED;
34 }
35 time = tv.tv_sec * MILLI_TO_SEC + tv.tv_nsec / NANO_TO_MILLI;
36 return E_TIME_OK;
37 }
38
GetBootTimeNs(int64_t & time)39 int32_t TimeUtils::GetBootTimeNs(int64_t &time)
40 {
41 struct timespec tv {};
42 if (!GetTimeByClockId(CLOCK_BOOTTIME, tv)) {
43 TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
44 return E_TIME_SA_DIED;
45 }
46 time = tv.tv_sec * NANO_TO_SEC + tv.tv_nsec;
47 return E_TIME_OK;
48 }
49
GetBootTimeMs(int64_t & time)50 int32_t TimeUtils::GetBootTimeMs(int64_t &time)
51 {
52 struct timespec tv {};
53 if (!GetTimeByClockId(CLOCK_BOOTTIME, tv)) {
54 TIME_HILOGE(TIME_MODULE_CLIENT, "get failed.");
55 return E_TIME_SA_DIED;
56 }
57 time = tv.tv_sec * MILLI_TO_SEC + tv.tv_nsec / NANO_TO_MILLI;
58 return E_TIME_OK;
59 }
60
GetTimeByClockId(clockid_t clockId,struct timespec & tv)61 bool TimeUtils::GetTimeByClockId(clockid_t clockId, struct timespec &tv)
62 {
63 if (clock_gettime(clockId, &tv) < 0) {
64 TIME_HILOGE(TIME_MODULE_CLIENT, "Failed clock_gettime, errno: %{public}s.", strerror(errno));
65 return false;
66 }
67 return true;
68 }
69
70 }
71 }