1 /*
2  * Copyright (c) 2022 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 "system_time.h"
17 
18 #include <atomic>
19 #include <sys/time.h>
20 
21 #include "log_print.h"
22 #include "platform_specific.h"
23 
24 namespace {
25     const uint64_t MULTIPLES_BETWEEN_SECONDS_AND_MICROSECONDS = 1000000;
26     std::atomic<int64_t> g_timeOffset(0);
27 }
28 
29 namespace DistributedDB {
30 namespace OS {
31 
32 #ifdef DB_DEBUG_ENV
GetCurrentSysTimeInMicrosecond(uint64_t & outTime)33 int GetCurrentSysTimeInMicrosecond(uint64_t &outTime)
34 {
35     struct timeval rawTime;
36     int errCode = gettimeofday(&rawTime, nullptr);
37     if (errCode < 0) {
38         LOGE("[GetSysTime] Fail:%d.", errCode);
39         return errCode;
40     }
41     outTime = static_cast<uint64_t>(rawTime.tv_sec) * MULTIPLES_BETWEEN_SECONDS_AND_MICROSECONDS +
42         static_cast<uint64_t>(rawTime.tv_usec);
43     outTime = outTime + static_cast<uint64_t>(g_timeOffset.load());
44     return 0;
45 }
46 #endif // DB_DEBUG_ENV
47 
SetOffsetBySecond(int64_t inSecond)48 void SetOffsetBySecond(int64_t inSecond)
49 {
50     int64_t microSecond = static_cast<int64_t>(inSecond) * MULTIPLES_BETWEEN_SECONDS_AND_MICROSECONDS; // to ms
51     g_timeOffset.store(microSecond);
52     LOGD("[SetTimeOffset] offset : %llds", inSecond);
53 }
54 }
55 }
56