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 <sleep_ex.h> 17 18#include <cstdlib> 19#include <ctime> 20#include <unistd.h> 21 22#define UNUSED(x) (void)(x) 23 24namespace SleepTest { 25 const long ID_MS_TO_NS_LEVEL = 1000000; // from milliseconds to nanoseconds 26 const int ID_SE_TO_MS_LEVEL = 1000; // from seconds to milliseconds 27} 28 29static double TimeDiff(struct timeval *x , struct timeval *y) 30{ 31 if (x == nullptr || y == nullptr) { 32 return 0; 33 } 34 35 double xUs = reinterpret_cast<double>(x->tv_sec * SleepTest::ID_MS_TO_NS_LEVEL) + 36 reinterpret_cast<double>(x->tv_usec); 37 double yUs = reinterpret_cast<double>(y->tv_sec * SleepTest::ID_MS_TO_NS_LEVEL) + 38 reinterpret_cast<double>(y->tv_usec); 39 40 return (yUs - xUs); 41} 42 43static int Nsleep(const struct timespec *req, struct timespec *rem) 44{ 45 struct timespec tempRem; 46 if (nanosleep(req, rem) == -1) { 47 Nsleep(rem, &tempRem); 48 return 0; 49 } 50 return 1; 51} 52 53int Msleep(unsigned long miliSec) 54{ 55 struct timespec req = {0, 0}; 56 struct timespec rem = {0, 0}; 57 time_t sec = reinterpret_cast<int>(miliSec / SleepTest::ID_SE_TO_MS_LEVEL); 58 miliSec = miliSec - (sec * SleepTest::ID_SE_TO_MS_LEVEL); 59 req.tv_sec = sec; 60 req.tv_nsec = miliSec * SleepTest::ID_MS_TO_NS_LEVEL; 61 Nsleep(&req, &rem); 62 return 1; 63} 64 65static void TmpFunc(const void* arg) 66{ 67 UNUSED(arg); 68} 69 70double ElapsedTime(time_callback func, void* arg) 71{ 72 struct timeval start; 73 struct timeval stop; 74 double diff; 75 double selfSpent; 76 77 if (func == nullptr) { 78 // error process here. 79 return 0.0; 80 } 81 82 // calc self spent. 83 gettimeofday(&start, 0); 84 TmpFunc(nullptr); 85 gettimeofday(&stop, 0); 86 selfSpent = TimeDiff(&start, &stop); 87 88 gettimeofday(&start, 0); 89 func(arg); 90 gettimeofday(&stop, 0); 91 diff = TimeDiff(&start, &stop); 92 93 diff = diff - selfSpent; 94 return (diff >= 0) ? diff : 0; 95} 96