Botan 3.14.1
Crypto and TLS for C&
time_utils.h
Go to the documentation of this file.
1/**
2* (C) 2024 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#ifndef BOTAN_TIME_UTILS_H_
8#define BOTAN_TIME_UTILS_H_
9
10#include <botan/exceptn.h>
11#include <botan/internal/target_info.h>
12#include <algorithm>
13#include <chrono>
14#include <limits>
15#include <optional>
16
17#if defined(BOTAN_HAS_OS_UTILS)
18 #include <botan/internal/os_utils.h>
19#endif
20
21namespace Botan {
22
23/**
24* Estimate the cost, in nanoseconds, of a single invocation of func
25*
26* Runs func repeatedly for roughly trial_msec (but always at least a few
27* times) and returns the fastest invocation observed. Interference from other
28* processes or threads can only ever make an invocation slower, so the minimum
29* is the best estimate of the cost of the work itself. Each invocation is timed
30* using the CPU time of the calling thread where available, otherwise using a
31* monotonic clock.
32*/
33template <typename F>
34uint64_t measure_cost(uint64_t trial_msec, F func) {
35#if defined(BOTAN_TARGET_OS_HAS_SYSTEM_CLOCK)
36 auto steady_ns = []() -> uint64_t {
37 const auto now = std::chrono::steady_clock::now().time_since_epoch();
38 return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(now).count());
39 };
40
41 auto thread_cpu_ns = []() -> std::optional<uint64_t> {
42 #if defined(BOTAN_HAS_OS_UTILS)
44 #else
45 return std::nullopt;
46 #endif
47 };
48
49 bool use_cpu_time = thread_cpu_ns().has_value();
50
51 const auto sample_ns = [&]() -> uint64_t {
52 if(use_cpu_time) {
53 return thread_cpu_ns().value_or(0);
54 }
55 return steady_ns();
56 };
57
58 constexpr size_t min_samples = 3;
59 const uint64_t trial_nsec = trial_msec * 1000000;
60 const uint64_t trial_start = steady_ns();
61
62 uint64_t best = std::numeric_limits<uint64_t>::max();
63 size_t samples = 0;
64
65 for(;;) {
66 const uint64_t start = sample_ns();
67 func();
68 const uint64_t end = sample_ns();
69
70 if(end > start) {
71 best = std::min(best, end - start);
72 samples += 1;
73 } else if(use_cpu_time) {
74 // The thread CPU clock cannot resolve a single invocation
75 use_cpu_time = false;
76 }
77
78 if(samples >= min_samples && (steady_ns() - trial_start) >= trial_nsec) {
79 return best;
80 }
81 }
82
83#else
84 BOTAN_UNUSED(trial_msec, func);
85 throw Not_Implemented("No system clock available");
86#endif
87}
88
89} // namespace Botan
90
91#endif
#define BOTAN_UNUSED
Definition assert.h:151
std::optional< uint64_t > BOTAN_TEST_API get_thread_cpu_time_ns()
Definition os_utils.cpp:345
uint64_t measure_cost(uint64_t trial_msec, F func)
Definition time_utils.h:34