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