guanaqo 1.0.0-alpha.29
Utilities for scientific software
Loading...
Searching...
No Matches
timed-cpu.cpp
Go to the documentation of this file.
2#include <ctime>
3#include <iomanip>
4
5#if defined(_WIN32)
6#include <Windows.h>
7#elif __has_include(<unistd.h>)
8#include <unistd.h>
9#endif
10
11namespace {
12
13int64_t getProcessCpuTime() {
14#if defined(_WIN32)
15 FILETIME creation_time, exit_time, kernel_time, user_time;
16 GetProcessTimes(GetCurrentProcess(), &creation_time, &exit_time,
17 &kernel_time, &user_time);
18 return static_cast<int64_t>(user_time.dwHighDateTime) << 32 |
19 user_time.dwLowDateTime;
20#elif defined(_POSIX_CPUTIME) && _POSIX_CPUTIME > 0
21 struct timespec cpu_time;
22 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &cpu_time);
23 return static_cast<int64_t>(cpu_time.tv_sec) * 1'000'000'000 +
24 cpu_time.tv_nsec;
25#else
26 using clock_duration =
27 std::chrono::duration<std::clock_t, std::ratio<1, CLOCKS_PER_SEC>>;
28 return std::chrono::duration_cast<std::chrono::nanoseconds>(
29 clock_duration{std::clock()})
30 .count();
31#endif
32}
33
34} // namespace
35
36namespace guanaqo {
37
38std::ostream &operator<<(std::ostream &os, TimingsCPU t) {
39 using millis_f64 = std::chrono::duration<double, std::milli>;
40 auto wall_ms = millis_f64(t.wall_time).count();
41 auto cpu_ms = millis_f64(t.cpu_time).count();
42 auto cpu_pct = 100 * cpu_ms / wall_ms;
43 auto prec = os.precision(6);
44 os << std::setw(8) << wall_ms << " ms (wall) ─ " //
45 << std::setw(8) << cpu_ms << " ms (CPU) ─ " //
46 << std::setprecision(5) << std::setw(7) << cpu_pct << "%";
47 os.precision(prec);
48 return os;
49}
50
52 wall_start_time = clock::now();
53 cpu_start_time = getProcessCpuTime();
54}
55
57 auto wall_end_time = clock::now();
58 auto cpu_end_time = getProcessCpuTime();
59 ++time.num_invocations;
60 time.wall_time += wall_end_time - wall_start_time;
61 time.cpu_time += std::chrono::nanoseconds{cpu_end_time - cpu_start_time};
62}
63
64} // namespace guanaqo
std::chrono::nanoseconds wall_time
Definition timed-cpu.hpp:20
std::chrono::nanoseconds cpu_time
Definition timed-cpu.hpp:21
std::ostream & operator<<(std::ostream &, TimingsCPU)
Definition timed-cpu.cpp:38
Measures the number of invocations of a specific piece of code and its run time.
Definition timed-cpu.hpp:18
clock::time_point wall_start_time
Definition timed-cpu.hpp:37
Timed(TimingsCPU &time)
Definition timed-cpu.cpp:51
CPU and wall-time measurements with RAII helper.