Raptor
A fast and space-efficient pre-filter
All Classes Namespaces Files Functions Variables Macros Pages Concepts
cpu_time.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2006-2024 Knut Reinert & Freie Universität Berlin
2// SPDX-FileCopyrightText: 2016-2024 Knut Reinert & MPI für molekulare Genetik
3// SPDX-License-Identifier: BSD-3-Clause
4
10#pragma once
11
12#include <algorithm>
13#include <cassert>
14#include <chrono>
15
16#if __has_include(<sys/resource.h>)
17# include <sys/resource.h>
18#endif
19
20namespace raptor
21{
22
24{
25 double user_time_in_seconds{};
26 double system_time_in_seconds{};
27
28 void operator-=(double const diff) noexcept
29 {
30 user_time_in_seconds -= diff;
31 }
32
33 [[nodiscard]] double cpu_usage_in_percent(double const elapsed_time_in_seconds,
34 uint8_t const threads) const noexcept
35 {
36 assert(is_valid());
37 assert(elapsed_time_in_seconds > 0.0);
38 return std::min<double>(100.0 * threads,
39 100.0 * (user_time_in_seconds + system_time_in_seconds) / elapsed_time_in_seconds);
40 }
41
42 [[nodiscard]] bool is_valid() const noexcept
43 {
44 return (user_time_in_seconds + system_time_in_seconds) >= 0.0;
45 }
46};
47
48#if __has_include(<sys/resource.h>)
49// Returns cpu_time_t{-1.0, -1.0} if not available.
50[[nodiscard]] inline cpu_time_t get_cpu_time()
51{
52 rusage usage;
53
54 if (getrusage(RUSAGE_SELF, &usage) != 0)
55 return cpu_time_t{-1.0, -1.0}; // GCOVR_EXCL_LINE
56
57 std::chrono::duration user_time =
58 std::chrono::seconds{usage.ru_utime.tv_sec} + std::chrono::microseconds{usage.ru_utime.tv_usec};
59 std::chrono::duration system_time =
60 std::chrono::seconds{usage.ru_stime.tv_sec} + std::chrono::microseconds{usage.ru_stime.tv_usec};
61
62 return cpu_time_t{.user_time_in_seconds = std::chrono::duration<double>(user_time).count(),
63 .system_time_in_seconds = std::chrono::duration<double>(system_time).count()};
64}
65#else
66[[nodiscard]] inline cpu_time_t get_cpu_time()
67{
68 return cpu_time_t{-1.0, -1.0};
69}
70#endif
71
72} // namespace raptor
T min(T... args)
Definition cpu_time.hpp:24
Hide me