• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "perfetto/base/build_config.h"
18 #include "perfetto/base/time.h"
19 
20 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
21 #include <Windows.h>
22 #else
23 #include <unistd.h>
24 #endif
25 
26 namespace perfetto {
27 namespace base {
28 
29 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
30 
GetWallTimeNs()31 TimeNanos GetWallTimeNs() {
32   LARGE_INTEGER freq;
33   ::QueryPerformanceFrequency(&freq);
34   LARGE_INTEGER counter;
35   ::QueryPerformanceCounter(&counter);
36   double elapsed_nanoseconds = (1e9 * counter.QuadPart) / freq.QuadPart;
37   return TimeNanos(static_cast<uint64_t>(elapsed_nanoseconds));
38 }
39 
GetThreadCPUTimeNs()40 TimeNanos GetThreadCPUTimeNs() {
41   FILETIME dummy, kernel_ftime, user_ftime;
42   ::GetThreadTimes(GetCurrentThread(), &dummy, &dummy, &kernel_ftime,
43                    &user_ftime);
44   uint64_t kernel_time = kernel_ftime.dwHighDateTime * 0x100000000 +
45                          kernel_ftime.dwLowDateTime;
46   uint64_t user_time = user_ftime.dwHighDateTime * 0x100000000 +
47                        user_ftime.dwLowDateTime;
48 
49   return TimeNanos((kernel_time + user_time) * 100);
50 }
51 
SleepMicroseconds(unsigned interval_us)52 void SleepMicroseconds(unsigned interval_us) {
53   // The Windows Sleep function takes a millisecond count. Round up so that
54   // short sleeps don't turn into a busy wait. Note that the sleep granularity
55   // on Windows can dynamically vary from 1 ms to ~16 ms, so don't count on this
56   // being a short sleep.
57   ::Sleep(static_cast<DWORD>((interval_us + 999) / 1000));
58 }
59 
60 #else  // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
61 
62 void SleepMicroseconds(unsigned interval_us) {
63   ::usleep(static_cast<useconds_t>(interval_us));
64 }
65 
66 #endif  // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
67 
68 }  // namespace base
69 }  // namespace perfetto
70