• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
18 
19 namespace OHOS {
20 namespace MiscServices {
21 namespace {
22 static constexpr int MILLI_TO_SEC = 1000LL;
23 static constexpr int NANO_TO_SEC = 1000000000LL;
24 constexpr int32_t NANO_TO_MILLI = NANO_TO_SEC / MILLI_TO_SEC;
25 }
26 
GetWallTimeMs(int64_t & time)27 int32_t TimeUtils::GetWallTimeMs(int64_t &time)
28 {
29     struct timespec tv {};
30     if (!GetTimeByClockId(CLOCK_REALTIME, tv)) {
31         TIME_HILOGE(TIME_MODULE_CLIENT, "get rt failed");
32         return E_TIME_SA_DIED;
33     }
34     time = tv.tv_sec * MILLI_TO_SEC + tv.tv_nsec / NANO_TO_MILLI;
35     return E_TIME_OK;
36 }
37 
GetBootTimeNs(int64_t & time)38 int32_t TimeUtils::GetBootTimeNs(int64_t &time)
39 {
40     struct timespec tv {};
41     if (!GetTimeByClockId(CLOCK_BOOTTIME, tv)) {
42         TIME_HILOGE(TIME_MODULE_CLIENT, "get bt failed");
43         return E_TIME_SA_DIED;
44     }
45     time = tv.tv_sec * NANO_TO_SEC + tv.tv_nsec;
46     return E_TIME_OK;
47 }
48 
GetBootTimeMs(int64_t & time)49 int32_t TimeUtils::GetBootTimeMs(int64_t &time)
50 {
51     struct timespec tv {};
52     if (!GetTimeByClockId(CLOCK_BOOTTIME, tv)) {
53         TIME_HILOGE(TIME_MODULE_CLIENT, "get bt failed");
54         return E_TIME_SA_DIED;
55     }
56     time = tv.tv_sec * MILLI_TO_SEC + tv.tv_nsec / NANO_TO_MILLI;
57     return E_TIME_OK;
58 }
59 
GetTimeByClockId(clockid_t clockId,struct timespec & tv)60 bool TimeUtils::GetTimeByClockId(clockid_t clockId, struct timespec &tv)
61 {
62     if (clock_gettime(clockId, &tv) < 0) {
63         TIME_HILOGE(TIME_MODULE_CLIENT, "Failed clock_gettime, errno: %{public}s", strerror(errno));
64         return false;
65     }
66     return true;
67 }
68 
69 }
70 }