1 /* 2 * Copyright (c) 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 "hks_util.h" 17 18 #include <time.h> 19 #include <unistd.h> 20 21 #define S_TO_MS 1000 22 #define MS_TO_NS 1000000 23 HksElapsedRealTime(uint64_t * timestampMs)24int32_t HksElapsedRealTime(uint64_t *timestampMs) 25 { 26 struct timespec curTime; 27 int32_t ret = clock_gettime(CLOCK_MONOTONIC, &curTime); 28 if (ret != 0) { 29 return ret; 30 } 31 32 if ((curTime.tv_sec >= (time_t)((UINT64_MAX - S_TO_MS) / S_TO_MS)) || (curTime.tv_nsec / MS_TO_NS >= S_TO_MS)) { 33 return -1; 34 } 35 36 *timestampMs = (uint64_t)(curTime.tv_sec * S_TO_MS + curTime.tv_nsec / MS_TO_NS); 37 return ret; 38 }