1 /*
2  * Copyright (C) 2021-2023 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 "hc_time.h"
17 #include <stdio.h>
18 #include <time.h>
19 #include "hc_log.h"
20 
21 #define SECOND_TO_MILLISECOND 1000
22 #define MILLISECOND_TO_NANOSECOND 1000000
23 
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27 
HcGetCurTime(void)28 int64_t HcGetCurTime(void)
29 {
30     struct timespec start;
31     int res = clock_gettime(CLOCK_MONOTONIC, &start);
32     if (res != 0) {
33         LOGE("[TIMER]: clock_gettime fail. [Res] :%d", res);
34         return -1;
35     }
36     return start.tv_sec;
37 }
38 
HcGetCurTimeInMillis(void)39 int64_t HcGetCurTimeInMillis(void)
40 {
41     struct timespec start;
42     int res = clock_gettime(CLOCK_MONOTONIC, &start);
43     if (res != 0) {
44         LOGE("[TIMER]: clock_gettime fail. [Res] :%d", res);
45         return -1;
46     }
47     return start.tv_sec * SECOND_TO_MILLISECOND + start.tv_nsec / MILLISECOND_TO_NANOSECOND;
48 }
49 
HcGetIntervalTime(int64_t startTime)50 int64_t HcGetIntervalTime(int64_t startTime)
51 {
52     if (startTime < 0) {
53         LOGE("Start time is invalid");
54         return -1;
55     }
56     struct timespec end;
57     int res = clock_gettime(CLOCK_MONOTONIC, &end);
58     if (res != 0) {
59         LOGE("[TIMER]: clock_gettime fail. [Res] :%d", res);
60         return -1;
61     }
62     if (end.tv_sec < startTime) {
63         LOGE("End time is invalid");
64         return -1;
65     }
66     return (end.tv_sec - startTime);
67 }
68 
69 #ifdef __cplusplus
70 }
71 #endif
72