1 /*
2  * Copyright (C) 2021 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 "nstackx_timer.h"
17 #include "nstackx_log.h"
18 #include "securec.h"
19 
20 #define TAG "nStackXTimer"
21 
GetTimeDiffMs(const struct timespec * etv,const struct timespec * stv)22 uint32_t GetTimeDiffMs(const struct timespec *etv, const struct timespec *stv)
23 {
24     uint64_t ms;
25 
26     if (etv->tv_sec < stv->tv_sec || (etv->tv_sec == stv->tv_sec && etv->tv_nsec < stv->tv_nsec)) {
27         LOGE(TAG, "invalid input: etv is smaller than stv");
28         return 0;
29     }
30 
31     if (etv->tv_nsec < stv->tv_nsec) {
32         ms = ((uint64_t)etv->tv_sec - (uint64_t)stv->tv_sec - 1) * NSTACKX_MILLI_TICKS;
33         ms += (NSTACKX_NANO_TICKS + (uint64_t)etv->tv_nsec - (uint64_t)stv->tv_nsec) / NSTACKX_MICRO_TICKS;
34     } else {
35         ms = ((uint64_t)etv->tv_sec - (uint64_t)stv->tv_sec) * NSTACKX_MILLI_TICKS;
36         ms += ((uint64_t)etv->tv_nsec - (uint64_t)stv->tv_nsec) / NSTACKX_MICRO_TICKS;
37     }
38     if (ms > UINT32_MAX) {
39         ms = UINT32_MAX;
40     }
41     return (uint32_t)ms;
42 }
43 
GetTimeDiffUs(const struct timespec * etv,const struct timespec * stv)44 uint32_t GetTimeDiffUs(const struct timespec *etv, const struct timespec *stv)
45 {
46     uint64_t us;
47     if (etv->tv_sec < stv->tv_sec || (etv->tv_sec == stv->tv_sec && etv->tv_nsec < stv->tv_nsec)) {
48         LOGE(TAG, "invalid input: etv is smaller than stv");
49         return 0;
50     }
51     if (etv->tv_nsec < stv->tv_nsec) {
52         us = ((uint64_t)etv->tv_sec - (uint64_t)stv->tv_sec - 1) * NSTACKX_MICRO_TICKS;
53         us += (NSTACKX_NANO_TICKS + (uint64_t)etv->tv_nsec - (uint64_t)stv->tv_nsec) / NSTACKX_NANO_SEC_PER_MICRO_SEC;
54     } else {
55         us = ((uint64_t)etv->tv_sec - (uint64_t)stv->tv_sec) * NSTACKX_MILLI_TICKS;
56         us += ((uint64_t)etv->tv_nsec - (uint64_t)stv->tv_nsec) / NSTACKX_NANO_SEC_PER_MICRO_SEC;
57     }
58     if (us > UINT32_MAX) {
59         us = UINT32_MAX;
60     }
61     return (uint32_t)us;
62 }
63