swift
cputime.cpp
1 // SPDX-FileCopyrightText: Copyright (C) 2019 swift Project Community / Contributors
2 // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3 
4 #include "misc/cputime.h"
5 
6 #include <QtGlobal>
7 
8 #if defined(Q_OS_WIN32)
9 # include <windows.h>
10 #elif defined(Q_OS_UNIX)
11 # include <time.h>
12 #endif
13 
14 namespace swift::misc
15 {
16 
17 #if defined(Q_OS_WIN32)
18 
19  static int getCpuTimeMs(const FILETIME &kernelTime, const FILETIME &userTime)
20  {
21  const ULARGE_INTEGER kernel { { kernelTime.dwLowDateTime, kernelTime.dwHighDateTime } };
22  const ULARGE_INTEGER user { { userTime.dwLowDateTime, userTime.dwHighDateTime } };
23  const quint64 usecs = (kernel.QuadPart + user.QuadPart) / 10ull;
24  return static_cast<int>(usecs / 1000ull);
25  }
27  {
28  FILETIME creationTime, exitTime, kernelTime, userTime;
29  GetProcessTimes(GetCurrentProcess(), &creationTime, &exitTime, &kernelTime, &userTime);
30  return getCpuTimeMs(kernelTime, userTime);
31  }
32  int getThreadCpuTimeMs()
33  {
34  FILETIME creationTime, exitTime, kernelTime, userTime;
35  GetThreadTimes(GetCurrentThread(), &creationTime, &exitTime, &kernelTime, &userTime);
36  return getCpuTimeMs(kernelTime, userTime);
37  }
38 
39 #elif defined(Q_OS_UNIX)
40 
41  static int getCpuTimeMs(const timespec &ts)
42  {
43  const double secs = static_cast<double>(ts.tv_sec) + static_cast<double>(ts.tv_nsec) / 1e9;
44  return static_cast<int>(secs * 1000);
45  }
47  {
48  timespec ts {};
49  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
50  return getCpuTimeMs(ts);
51  }
52  int getThreadCpuTimeMs()
53  {
54  timespec ts {};
55  clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
56  return getCpuTimeMs(ts);
57  }
58 
59 #else // Q_OS_UNIX
60 
62  {
63  return 0; // not implemented
64  }
66  {
67  return 0; // not implemented
68  }
69 
70 #endif
71 
72 } // namespace swift::misc
Free functions in swift::misc.
int getProcessCpuTimeMs()
Get the time in milliseconds that the CPU has spent executing the current process.
Definition: cputime.cpp:61
int getThreadCpuTimeMs()
Get the time in milliseconds that the CPU has spent executing the current thread.
Definition: cputime.cpp:65